首先,是否有可能在 客户端 使用 JavaScript 在 asp:GridView 中循环访问数据。如果是的,我想知道该怎么做...
因为我打算捕获网格上 2 个字段的值,并根据它们的值在每一行上附加一个图像(一旦我可以循环遍历数据,那部分应该不会造成太大问题并比较它们)。
我的网格看起来像这个:
<asp:GridView ID="GridView1" runat="server" EmptyDataText="No Record Found" AllowSorting="true"
AllowPaging="false" OnRowCreated="GridView1_RowCreated" Visible="true" BackColor="ButtonShadow"
OnSorting="GridView1_Sort" AutoGenerateColumns="false" GridLines="None" >
<Columns>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Exam" HeaderText="Exam" SortExpression="Exam" />
<asp:BoundField DataField="DateTime" HeaderText="DateTime" SortExpression="DateTime" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:BoundField DataField="Priority" HeaderText="Priority" SortExpression="Priority" />
</Columns>
</asp:GridView>
如果我直截了当:我如何为每一行捕获性别和年龄?
P.S. 我也对 JQuery 解决方案持开放态度......
最佳答案
因为您拥有 gridview 的 id
,您可以在 Javascript 中获取元素,遍历其行,然后遍历行的单元格,检查索引 1(性别)或 2(年龄) ), 并获取其 innerHTML
以获取内容。看看这个:
window.onload = function () {
var table, tbody, i, rowLen, row, j, colLen, cell;
table = document.getElementById("GridView1");
tbody = table.tBodies[0];
for (i = 0, rowLen = tbody.rows.length; i < rowLen; i++) {
row = tbody.rows[i];
for (j = 0, colLen = row.cells.length; j < colLen; j++) {
cell = row.cells[j];
if (j == 1) {
// Gender
console.log("--Found gender: " + cell.innerHTML);
} else if (j == 2) {
// Age
console.log("--Found age: " + cell.innerHTML);
}
}
}
};
演示: http://jsfiddle.net/ZRXV3/
这绝对取决于呈现的 HTML 的结构。总有一个隐藏的列或其他东西。
更新:
jQuery 解决方案可能是这样的:
$(document).ready(function () {
var rows, genders, ages;
rows = $("#GridView1").children("tbody").children("tr"); // Find all rows in table (content)
genders = rows.children("td:nth-child(2)"); // Find all columns that are the 2nd child
ages = rows.children("td:nth-child(3)"); // Find all columns that are the 3rd child
// An example of looping through all "gender" columns
genders.each(function () {
console.log($(this).html());
});
});
关于javascript - 循环遍历 asp :GridView data using javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12937122/