javascript 删除元素的父行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17855977/
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
Remove element's parent row
提问by Fireworm
I have a table with buttons in cells, like so:
我有一个单元格中有按钮的表格,如下所示:
<table>
<tr>
<td>information</td>
<td>
<button onclick="function(id, this)">Text</button>
</td>
</tr>
</table>
The function called when the button is pressed does some ajax stuff, and if it's successful, the whole row where the button is should be removed from the DOM. (It's a delete function ;)
按下按钮时调用的函数会执行一些 ajax 操作,如果成功,应该从 DOM 中删除按钮所在的整行。(这是一个删除功能;)
However, I can't seem to get jQuery to remove the correct row.
I've used $('#id').parent().parent().remove();
, as I thought it would go: button -> cell -> row, but it just removes the first row of the table?! Wherever did I lose? :(
但是,我似乎无法让 jQuery 删除正确的行。我用过$('#id').parent().parent().remove();
,因为我认为它会去:按钮 -> 单元格 -> 行,但它只是删除了表格的第一行?!我哪里输了?:(
回答by SmokeyPHP
<table>
<tr>
<td>information</td>
<td>
<button onclick="removeRow(this)">Text</button>
</td>
</tr>
<tr>
<td>blah</td>
<td>
<button onclick="removeRow(this)">Text</button>
</td>
</tr>
</table>
JavaScript
JavaScript
removeRow = function(el) {
$(el).parents("tr").remove()
}
回答by Mohammad Adil
.closest()
can do that easily -
.closest()
可以轻松做到——
$(this).closest('tr').remove();
You can remove inline onClick and handle the click like this -
您可以删除内联 onClick 并像这样处理点击 -
$('button').on('click',function(){
$(this).closest('tr').remove();
});
Demo ------>
http://jsfiddle.net/2nJYe/
演示------>
http://jsfiddle.net/2nJYe/
回答by Tushar Gupta - curioustushar
Working Demo http://jsfiddle.net/cse_tushar/6mMkM/
工作演示http://jsfiddle.net/cse_tushar/6mMkM/
$('.b1').click(function () {
$(this).parent().parent().remove();
});
回答by schnill
you have done this right but there is no id, if you do this it'll work as you expected,
你做对了,但没有id,如果你这样做,它会按你预期的那样工作,
$(this).parent().parent().remove();
but using .closest() is recommended in such situation.
但是在这种情况下建议使用 .closest() 。
$(this).closest("tr").remove();