jQuery函数在append()之后没有响应

我正在创建一系列div框,允许用户使用jQuery从每个框中添加/删除项目。 我发现在向框中添加新元素后,我绑定到该元素的单击函数将不会响应。 这大致是我的代码的样子:

$(".add").click(function() { $("#targetbox").append("This element was added"); }); $(".remove").click(function() { alert("removing"); $(this).remove(); }); 

如果我使用项目预填充#targetbox,它们会响应clickfunction。 它只是动态添加的项目,不响应该function。

将click方法直接添加到新添加的元素中

 $(".add").click(function() { $("#targetbox").append("This element was added") .bind("click",function(e) { alert("removing"); $(this).remove(); }); }); 

或者使用.live()方法,在附加任何新的.remove元素后将为您绑定click事件

 $(".add").click(function() { $("#targetbox").append("This element was added"); }); $(".remove").live("click", function() { alert("removing"); $(this).remove(); }); 

您的代码处理当前$('.remove')所有元素的click事件。
任何尚不存在的元素都不会受到影响。

您需要调用.live().delegate方法,这些方法将处理与选择器匹配的所有元素的事件,无论它们何时被创建。

例如:

 $(".remove").live('click', function() { alert("removing"); $(this).remove(); }); 

这是因为当您的代码运行时,项目尚未添加。 在添加单击function期间添加后,需要添加删除单击function以动态分配给新块。

 $(".add").click(function() { $("#targetbox").append("This element was added"); // Add code here for .remove click function });