动态添加Jquery删除按钮不起作用

时间:2012-06-06 06:59:48

标签: jquery button document-ready

毫无疑问这很简单,但是我对jquery缺乏了解,这对我来说很复杂。基本上我有这个代码:

$(document).ready( 
    function() {
    $( "#remove")
    .click(function() {
        alert("I have been clicked!");
        $(this).parent().parent().remove();
    }); 
});

我在表格中添加了一个按钮,用于删除它的行(参见上面的代码)。按钮如下:

<td ><button id='remove' type='button'>Remove</button></td>

然而,点击时它什么都不做。我认为这可能与文档加载后创建按钮的事实有关...但不知道如何处理它。

1 个答案:

答案 0 :(得分:5)

$( "td").on('click', '#remove', function() {
        alert("I have been clicked!");
        $(this).parent().parent().remove();
    }); 

当您尝试动态添加按钮时,您需要委托事件处理程序(也称为直播事件)。

jQuery&gt; 1.7 委托事件声明为

$(container).on(eventName, target, handlerFunction);

有关详细信息,请参阅.on()

您有另一个名为.delegate()的选项,其声明流程为:

$(container).delegate(target, eventName, handlerFunction);

因此,对于您的情况,它将如下所示:

$('td').delegate('#remove', 'click', function() {
      alert("I have been clicked!");
      $(this).parent().parent().remove();
});

注意

此处container表示#remove按钮的持有者,在页面加载时属于DOM。从您发布的内容看似td,您可能还有其他内容(任何有效的jQuery selectors

如果您container无法检测到#remove,请使用$(document)$('body')代替$('td')