使用jQuery查找表格行索引
问题描述:
我是jQuery中的中间用户。我知道使用jQuery来查找表的rowIndex,但我的场景是不同的。我的表(GridView)由20列组成,每列都有不同的控件,如文本框,下拉列表,图像,标签。所有是每行中的服务器端控件。我将gridview与数据库中的记录绑定在一起。现在,当我点击任何文本框的任何控件或onchange时,我需要获取该已更改列的行的rowIndex。这里是我的用户代码:使用jQuery查找表格行索引
$("#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
答
这是表中的小区中的复选框时,有变化:
var row = $(this).parent().parent();
var rowIndex = $(row[0].rowIndex);
console.log(rowIndex);
答
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或跨度包裹你的内部单元格,你可能会搞砸这个关系。 .closest()
是确保它始终有效的简单方法。
当然,我的代码示例重新使用上面提供的示例。你可能希望先用一个更简单的选择器进行测试,以证明它的工作原理,然后优化你的选择器。
答
应该能够只使用:
var rowIndex = $(this).parents("tr:first")[0].rowIndex;
但我想要得到的改变文本框的rowIndex位置? – superachu 2009-10-25 11:50:22
你能否提供你的页面的HTML? – 2009-10-25 14:39:35