使用jQuery删除动态添加的div无效

3
我在按钮点击时添加了一个div,我希望用户能够通过单击“X”(一个锚点)来从列表中删除已添加的项目,但是单击事件没有触发。这是我的代码,我甚至尝试过绑定,但似乎都不起作用。
(function ( $ ) { 
$(document).ready(function(){
$(".btn-add").on("click",function() {
var $row = $(this).closest("tr"); // Find the row
var $text = $row.find(".this-name").text(); // Find the text

// Let's test it out
$('#col2').append('<div class="item"><p>'+$text+'</p><a href="#" class="delete-button">X</a></div>');
});

});

$("document").on('click','.delete-button', function(e){
 e.preventDefault();
 alert('yes');
 $(this).closest('.item').remove();
});

}( jQuery ));

非常感谢,欢迎提供任何帮助。


1
这是 document,不是 "document" - Ameya Deshpande
1
请您添加相关的 html 代码,以便我们可以复制这个。 - Guruprasad J Rao
1
Syed - 你修改了问题中的句点,但没有删除引号。 - nnnnnn
1
“引号是问题所在,我感觉好蠢。现在它正常工作了,谢谢@AmeyaDeshpande。有时候你只需要别人的一双眼睛来解决错误 :)” - Syed Haris Ali Ghaznavi
有一瞬间,我想说,“你在匿名函数中将文档点击事件绑定到尚未插入到DOM中的目标上了。” - Joshua
1个回答

2
尝试这个:onClick="$(this).parent().remove();"。它可以删除父元素。
(function ( $ ) { 
$(document).ready(function(){
     $(".btn-add").on("click",function() {
         var $row = $(this).closest("tr"); // Find the row
         var $text = $row.find(".this-name").text(); // Find the text
         // Let's test it out
         $('#col2').append('<div class="item"><p>'+$text+'</p><a href="#" class="delete-button" onClick="$(this).parent().remove();">X</a></div>');
     });
});
$(document).on('click','.delete-button', function(e){
    e.preventDefault();
    alert('yes');
    $(this).closest('.item').remove();
});
}( jQuery ));

请注意,我已经为锚点“X”本身添加了Onlcik代码。 - user7488658

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接