使用jQuery查找表行索引

时间:2009-10-25 08:47:17

标签: jquery indexing row

我是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?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:9)

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

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

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

这将为您返回正确的行索引。此外,如果您要使用jQuery的.closest()函数来遍历DOM以及.parent(),为什么不对这两个函数进行求解并只遍历最近的<tr>元素?

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

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

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

答案 2 :(得分:4)

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

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

答案 3 :(得分:2)

应该可以使用:

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