使用jQuery查找表行索引

我是jQuery的中间用户。 我知道使用jquery找到表的rowIndex,但我的场景是另一个。 我的表(GridView)由20列组成,每列包含不同的控件,如文本框,下拉列表,图像,标签。 所有都是每行中的服务器端控件。 我将gridview与数据库中的记录绑定在一起。 现在当我点击任何控件或任何文本框的更改时,我需要获取该更改列的行的rowIndex。 这是我用户的代码:

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

但我无法获得rowIndex。 如果我在gridview中使用任何html控件,我就能得到rowIndex。 当点击gridview中的服务器控件时,有没有办法找出rowIndex?

试试这个:

 var rowIndex = $(this) .closest('tr') // Get the closest tr parent element .prevAll() // Find all sibling elements in front of it .length; // Get their count 

sectionRowIndex

元素的属性,而不是属性。

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

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

这将为您返回正确的行索引。 另外,如果你要使用jQuery的.closest()函数遍历DOM以及.parent() ,为什么不编译这两个并只遍历最近的

元素?

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

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

当然,我的代码示例正在重复使用上面提供的示例。 您可能希望首先使用更简单的选择器进行测试以certificate其有效,然后优化您的选择器。

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

  var row = $(this).parent().parent(); var rowIndex = $(row[0].rowIndex); console.log(rowIndex); 

应该可以只使用:

 var rowIndex = $(this).parents("tr:first")[0].rowIndex;