15

我是 jQuery 的中级用户。我知道使用 jQUery 查找表的 rowIndex,但我的情况是不同的。我的表(GridView)由 20 列组成,每列都有不同的控件,如文本框、下拉列表、图像、标签。每行都是服务器端控件。我将 gridview 与数据库中的记录绑定。现在,当我单击任何控件或任何文本框的 onchange 时,我需要获取已更改列的行的 rowIndex。这是我使用的代码:

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){
   alert($(this).closest('td').parent().attr('sectionRowIndex'));
});

但我无法获得rowIndex。如果我在 gridview 中使用任何 html 控件,我就可以获得 rowIndex。单击gridview中的服务器控件时,有什么方法可以找出rowIndex?

4

4 回答 4

44

尝试这个:

var rowIndex = $(this)
    .closest('tr') // Get the closest tr parent element
    .prevAll() // Find all sibling elements in front of it
    .length; // Get their count
于 2009-10-25T08:51:40.407 回答
9

sectionRowIndex<tr>元素的属性,而不是属性。

修改示例代码的正确方法是使用零索引器访问 jQuery 项,如下所示:

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){
   alert($(this).closest('td').parent()[0].sectionRowIndex);
});

这将为您返回正确的行索引。另外,如果您打算使用 jQuery 的.closest()函数来遍历 DOM 和 DOM .parent(),为什么不将这两者结合起来,只遍历最近的<tr>元素呢?

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){
   alert($(this).closest('tr')[0].sectionRowIndex);
});

这也将处理父->子关系不完全符合您预期的奇怪情况。例如,如果你链接 a$(this).parent().parent()然后决定用另一个 div 或 span 包裹你的内部单元格,你可能会搞砸关系。这.closest()是确保它始终有效的简单方法。

当然,我的代码示例正在重新使用您上面提供的示例。您可能希望先使用更简单的选择器进行测试以证明它有效,然后再改进您的选择器。

于 2011-11-24T21:43:43.427 回答
4

这是表格单元格中的复选框,在更改时:

 var row = $(this).parent().parent();
 var rowIndex = $(row[0].rowIndex);
 console.log(rowIndex);
于 2011-06-24T15:39:06.377 回答
2

应该能够使用:

var rowIndex = $(this).parents("tr:first")[0].rowIndex;
于 2014-11-10T19:17:54.370 回答