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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:26:08  来源:igfitidea点击:

jQuery basic: How can i remove a table row when a button of this row is clicked?

jquery

提问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 .liveto bind your event will bind it automatically when your row is dynamically added.

使用.live绑定你的事件将自动绑定它时动态添加的行。

Edit

编辑

liveis now deprecated, since version 1.7 I think.

live现在已弃用,因为我认为是 1.7 版。

The way to go now is using oninstead 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())});