【问题标题】:Get Columns Name or Header Text of GridView Using JavaScript使用 JavaScript 获取 GridView 的列名称或标题文本
【发布时间】:2013-06-13 07:25:10
【问题描述】:

我正在开发一个 Web 应用程序,我需要使用 javascript 列的网格视图名称。之后,在 Div 上显示该列的名称。

请帮我解决这个问题。

【问题讨论】:

    标签: javascript asp.net gridview


    【解决方案1】:

    没有标准的方法可以做到这一点。 GridView 只不过是运行时的 html 表。所以你能做的最好的就是通过 javascript 抓取这个表并抓取它的列。

    假设,你已经像这样声明了你的gridview

    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    

    并像这样在运行时绑定它:

            DataTable dt= new DataTable();
            db.Columns.Add("Col1");
            db.Columns.Add("Col2");
    
            db.Rows.Add("one", "two");
            GridView1.DataSource = dt;
            GridView1.DataBind();
    

    然后在运行时,为您的gridView 生成如下标记

    <table cellspacing="0" rules="all" border="1" id="GridView1" 
           style="border-collapse:collapse;">
         <tr>
             <th scope="col">Col1</th>
             <th scope="col">Col2</th>
         </tr>
         <tr>
            <td>one</td>
            <td>two</td>
        </tr>
    </table>
    

    很明显,列是GridView 表中的th 元素,您可以通过javascript 轻松获取,如下所示:

    var table = document.getElementById('GridView1');
    var headers = table.getElementsByTagName('th');
    
    for(var i=0;i<headers.length;i++)
    {
        alert(headers[i].innerText);
        //or append to some div innerText
    }
    

    请参阅this fiddle 了解如何抓取表格元素

    【讨论】:

    • 你好 Manish Mishra,谢谢
    • 嘿 Manish,我传递了我的 GridId 它没有给出我的 ID var table = document.getElementById('');警报(表);
    • 嗨,Manish Mishra。我可以将此标题与清单框绑定吗我正在这样做但它不起作用...
    【解决方案2】:

    GridView 在您的页面源代码中呈现为 HTML 表,因此您可以使用 Jquery 来获取、查看源代码并检查它是否与任何类关联,然后您可以将其用作选择器,或者常规 $('table tr th') 这篇文章可能帮你How to get a table cell value using jQuery?

    【讨论】:

    • 你好 Vishal Sachdeva,谢谢,但我不想要 jquery 我只想使用 javascript
    • 我不认为两者有什么区别 Jquery 是一个使用 JS 开发的库来帮助你减少语法,仅此而已 document.getElementById('ID') 被写入 $('# ID')。
    猜你喜欢
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    相关资源
    最近更新 更多