jQuery 如何使用jQuery知道<table>中<tr>的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1858175/
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
How to know index of a <tr> inside a <table> with jQuery?
提问by user198729
回答by CMS
If you defined the click handler directly on the tr
elements, you can use the index
method like this:
如果直接在tr
元素上定义点击处理程序,则可以使用如下index
方法:
$('#tableId tr').click(function () {
var rowIndex = $('#tableId tr').index(this); //index relative to the #tableId rows
});
If the click event is bound not directly on the tr
element (if you are using an anchor, a button, etc...), you should find the closest tr
to get the right index:
如果单击事件不是直接绑定在tr
元素上(如果您使用的是锚点、按钮等...),您应该找到最接近的tr
以获得正确的索引:
$(selector).click(function () {
var rowIndex = $('#tableId tr').index($(this).closest('tr'));
return false;
});
Try an example here.
在这里尝试一个例子。
回答by cletus
To answer your first question:
回答你的第一个问题:
$("#id tr").click(function() {
alert($("#id tr").index(this));
});
If you just do:
如果你只是这样做:
$("table tr").index(this);
and you have multiple tables on the page, you will get an erroneous result.
如果页面上有多个表,则会得到错误的结果。
That being said, you don't need to know the index to move rows up and down in a table. For example:
话虽如此,您无需知道索引即可在表中上下移动行。例如:
<table id="foo">
<tr>
<td><a href="#" class="up">Up</a> <a href="#" class="down">down</a></td>
<td>First row</td>
</tr>
<tr>
<td><a href="#" class="up">Up</a> <a href="#" class="down">down</a></td>
<td>Second row</td>
</tr>
<tr>
<td><a href="#" class="up">Up</a> <a href="#" class="down">down</a></td>
<td>Third row</td>
</tr>
</table>
with something like:
像这样:
$("a.up").click(function() {
var row = $(this).closest("tr");
if (row.prev().length > 0) {
row.insertBefore(row.prev());
}
return false;
});
$("a.down").click(function() {
var row = $(this).closest("tr");
if (row.next().length > 0) {
row.insertAfter(row.next());
}
return false;
});
回答by TM.
This should work:
这应该有效:
$('#tableId tr').click(function () {
var index = $(this).siblings('tr').index(this);
});
You don't need tr
in the call to siblings
if you are sure your html will be well-formed.
如果您确定您的 html 格式正确tr
,siblings
则不需要调用。