jQuery 基础:如何在单击该行的按钮时删除表格行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6831394/
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
jQuery basic: How can i remove a table row when a button of this row is clicked?
提问by prime
$("#tableid tbody:last").append(html);
This creates table rows dynamically. Each newly created row has a "remove" button.
这会动态创建表行。每个新创建的行都有一个“删除”按钮。
Now if i click that remove button that row will be deleted. How can i do this.
现在,如果我单击该删除按钮,该行将被删除。我怎样才能做到这一点。
Thanks in advance.
提前致谢。
回答by Johnny5
$(buttonSelector).live ('click', function ()
{
$(this).closest ('tr').remove ();
}
);
using .live
to bind your event will bind it automatically when your row is dynamically added.
使用.live
绑定你的事件将自动绑定它时动态添加的行。
Edit
编辑
live
is now deprecated, since version 1.7 I think.
live
现在已弃用,因为我认为是 1.7 版。
The way to go now is using on
instead of live
.
现在要走的路是使用on
而不是live
.
$('#tableid').on('click', buttonSelector, function(){
$(this).closest ('tr').remove ();
});
See the doc.
请参阅文档。
回答by Justin Ethier
You can use this code to delete the parent row containing the clicked button:
您可以使用此代码删除包含单击按钮的父行:
$(myButtonSelector).click(function(){
$(this).parents('tr').first().remove();
});
For a live example see this link.
有关现场示例,请参阅此链接。
For more information see this article.
有关详细信息,请参阅本文。
回答by Brian Hoover
You could do something like:
你可以这样做:
$('.add').click(function(){
$("#tableid tbody:last").append('<tr><td>Hi</td><td><a class="remove">Remove</a>');
});
$('.remove').live('click',function(){console.log($(this).parent().parent().remove())});