[英]Jquery: Removing dynamically generated element when modal confirmation button is clicked
[英]Removing dynamically generated elements, when clicking on an element within itself in jQuery?
单击其中的按钮时,如何删除动态生成的元素块?
function controlContent(target, trigger) {
//this will add a new div to target which is an existing html element
$(trigger).on("click", () => {
$(target).append(`
<div class="dynamic-container">
<button class="remove-btn">Remove the div I am inside</button>
</div>
`)
}
//this should remove the div that was added when I click the remove button
$(target).on("click", ".remove-btn", () => {
$(this).closest(".dynamic-container").remove();
}
}
使用普通的 function 并使用动态点击侦听器,因此您无需每次都创建新的事件列表器。
$(document).on('click', '.remove-btn', function(){
$(this).closest(".dynamic-container").remove();
})
第一:你应该使用$(document).on("click", target, function(){...}
动态生成的元素
第二:像parent()
一样简单
$(document).on("click", target, function(){
$(this).parent().remove();
});
例子:
$(".button1").on("click", function(){ $(".generatedbuttons").append('<div class="green"><button class="button2">Click me to remove me and my parent</button></div>'); }); $(document).on("click", ".button2", function(){ $(this).parent().remove(); });
.button1 { display:block; float: left; }.green { padding: 10px; background-color: green; display: block; float: left; clear: both; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="button1">Click me to generate buttons</button> <div class="generatedbuttons"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.