10

我想找到单击按钮的行。

<table>
  <tr>
    <td>foo 1</td>
    <td><input  type="button" value="Remove" id="remove1"/> </td>
  </tr>
  <tr>
    <td>foo 2 </td>
    <td><input  type="button" value="Remove" id="remove2"/> </td>
  </tr>
</table>

我的表结构如上所示。通常我可以使用 buttonid 来获取行索引。但是如果我删除一行(tr),另一个行索引会发生变化。例如:

如果我用 jQuery 删除第一行,第二行索引更改为 0,那么我不能使用按钮的 id。(删除 - 2 )

好吧,我认为我必须使用父函数,但它不起作用。

var elem = $('#remove2');
alert(elem.parent()[0].sectionRowIndex);

我试过这个,但没有用。我需要在行中单击按钮的行索引。

我希望我解释了我的问题。

4

4 回答 4

21

尝试这个:

$("table tr input").on('click', function(e){
   alert($(this).closest('td').parent()[0].sectionRowIndex);
});​

小提琴

于 2013-01-01T17:52:37.730 回答
6

尝试使用这个:http: //jsfiddle.net/jd9N4/1/

var elem = $('input[type="button"]');
$(elem).click(function() {
   alert($(this).closest('tr').index());
   $(this).closest('tr').remove();
});
于 2013-01-01T17:52:18.187 回答
2

你不需要ID

$('table').on('click', 'input[value="Remove"]', function(){
  $(this).closest('tr').remove();
});
于 2013-01-01T17:50:25.223 回答
2

如果您要动态添加行,则可以

 $(document).on('click', 'button', function () {
     var indexRow = this.parentNode.parentNode.rowIndex;
     document.getElementById("table-name").deleteRow(indexRow);
 });
于 2017-06-12T06:19:26.580 回答