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

标签 javascript jquery events onclick

我在按钮单击上添加了 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/

相关文章:

javascript - 在内部,每个数组元素如何传递给 javascript 中 "map"函数内部使用的回调函数

javascript - 检查 less 文件是否存在

jquery - 设置新元素的位置,同时悬停元素

java - Spring + JQuery 动态绑定(bind)

javascript - $.Deferred 作为成员变量

.net - VB.NET中事件的GetInvocationList

Java JComboBox 下拉事件

javascript - 将挖空 View 模型绑定(bind)到 Bootstrap Tree View

javascript - 导入到 Three.js 后,Blender 动画变得扭曲

android - 设备开机或解锁时启动应用程序