jQuery 单击表中的按钮时如何查找行索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14112721/
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:16:43  来源:igfitidea点击:

How to find rowindex when clicked a button in table

jqueryhtml-table

提问by ertan2002

I want to find row which clicked button in.

我想找到点击按钮的行。

<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>

My table struct is like above. Normally I can us buttonid to get row index. But If I remove a row (tr) another row index changes. For example:

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

If I remove first row with jQuery, second row index changes as 0 then I cannot use button's id. (remove - 2 )

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

Well I think that I must use parent function but it doesn't work.

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

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

I tried this one but doesn't work. I need row index that clicked button in the row.

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

I hope that I explained my issue.

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

回答by pala?н

Try this:

尝试这个:

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

FIDDLE

小提琴

回答by Jai

Try using this: http://jsfiddle.net/jd9N4/1/

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

var elem = $('input[type="button"]');
$(elem).click(function() {
   alert($(this).closest('tr').index());
   $(this).closest('tr').remove();
});

回答by Roko C. Buljan

You don't need ID

你不需要 ID

$('table').on('click', 'input[value="Remove"]', function(){
  $(this).closest('tr').remove();
});

回答by Mahendra Waykos

IF you are adding row dynamically you can

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

 $(document).on('click', 'button', function () {
     var indexRow = this.parentNode.parentNode.rowIndex;
     document.getElementById("table-name").deleteRow(indexRow);
 });