使用JavaScript获取GridView的列名称或标题文本

时间:2013-06-13 07:25:10

标签: javascript asp.net gridview

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

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

GridView在页面源上呈现为HTML表格,因此您可以使用Jquery获取,查看源代码并检查它是否与任何类关联,然后您可以将其用作选择器,或定期$('table tr th')这个帖子可以帮助你How to get a table cell value using jQuery?

答案 1 :(得分:0)

没有标准的方法可以这样做。 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>

如此清楚,列是th表中的GridView元素,您可以轻松地通过以下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了解如何抓取表格元素

相关问题