开发者

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

I'm now implementing something like this post (specifically, the effect takes place when the row is clicke开发者_如何学Pythond)

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


If you defined the click handler directly on the tr elements, you can use the index method like this:

$('#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:

$(selector).click(function () {
  var rowIndex = $('#tableId tr').index($(this).closest('tr'));

  return false;
});

Try an example here.


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.


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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜