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

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

How to know index of a <tr> inside a <table> with jQuery?

jqueryhtml

提问by user198729

I'm now implementing something like this post(specifically, the effect takes place when the row is clicked)

我现在正在实施类似这篇文章的内容(具体来说,点击行时会发生效果)

How do I know what the index of the row is inside the table?

我怎么知道表内行的索引是什么?

回答by CMS

If you defined the click handler directly on the trelements, you can use the indexmethod 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 trelement (if you are using an anchor, a button, etc...), you should find the closest trto 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 trin the call to siblingsif you are sure your html will be well-formed.

如果您确定您的 html 格式正确trsiblings则不需要调用。