我在按钮单击上添加了 div,我希望用户能够通过单击“X”( anchor )从列表中删除添加的项目,但单击时不会触发任何事件,这是我的代码,我什至尝试过绑定(bind),但似乎没有任何效果。
(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 ));
感谢任何帮助,谢谢
最佳答案
试试这个: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 ));
关于javascript - 使用 jQuery 删除 div 不适用于动态添加的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41930589/