gpt4 book ai didi

javascript - 在 jQuery 中单击自身内的元素时删除动态生成的元素?

转载 作者:行者123 更新时间:2023-11-28 04:43:39 25 4
gpt4 key购买 nike

如何在单击其中的按钮时删除动态生成的元素 block ?

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();
}
}

最佳答案

首先:对于动态生成的元素,您应该使用$(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>

关于javascript - 在 jQuery 中单击自身内的元素时删除动态生成的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com