jQuery - 在其更改处理程序中查找当前选择元素的行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2410421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:27:27  来源:igfitidea点击:

jQuery - Finding the row number of the current select element within its change handler

jqueryhtml-table

提问by loviji

I have a table. In this table have select element. How can I find in which table row is select element, from within the select's event handler:

我有一张桌子。在这个表中有选择元素。如何从 select 的事件处理程序中找到哪个表格行是 select 元素:

$('#selectElemID').live('change', function(){...});

Thanks

谢谢

回答by karim79

EDIT (two years later): Please don't do it the way I previously described, it is a total waste as table rows already have a rowIndexproperty, so there's just no need to compute anything:

编辑(两年后):请不要像我之前描述的那样做,这完全是浪费,因为表行已经有一个rowIndex属性,所以不需要计算任何东西:

$('#selectElemID').live("change", function (){
    alert($(this).closest("tr")[0].rowIndex);
});

Demo.

演示。

<silliness>

<silliness>

This should do it, if you want the row number of the current select element (which is what I understand from the question):

如果您想要当前选择元素的行号(这是我从问题中理解的),应该这样做:

$('#selectElemID').live('change', function(){
    alert($(this).closest("tr").prevAll("tr").length + 1);
});

To explain:

解释:

$(this).closest("tr")

means select the closest parent trof this select element.

表示选择tr此 select 元素的最近父级。

.prevAll("tr").length + 1

means select all the previousrows, and get me the length of the returned collection. Increment it by one to get the current row number, because we are at total previous rows + 1.

意味着选择所有前面的行,并获取返回集合的长度。将其增加 1 以获得当前行号,因为我们总共有前几行 + 1

For more information:

想要查询更多的信息:

</silliness>

</silliness>

回答by BbErSeRkK

also:

还:

$('#selectElemID').live('change', function(){
    alert($(this).closest("tr")[0].rowIndex);
});