使用jQuery删除div不适用于动态添加的div

时间:2017-01-30 07:11:09

标签: javascript jquery events onclick

我在单击按钮时添加了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 个答案:

答案 0 :(得分:0)

试试这个:onClick =&#34; $(this).parent()。remove();&#34;

(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 ));
相关问题