gpt4 book ai didi

javascript - 如何动态删除javascript中的元素?

转载 作者:行者123 更新时间:2023-12-01 01:56:19 25 4
gpt4 key购买 nike

有没有办法用 javascript 或 jquery 动态删除元素。假设我有一个函数 createElements() 来创建新元素,另一个函数removeElement() 则假设删除相应的元素。您会注意到,当您运行代码片段时,当您单击删除按钮时,所有元素都消失了!我怎样才能实现这段代码?是否有一个jquery选择器可以让我简单地使用removeElement(this)或类似的东西?非常欢迎任何建议:) 谢谢。

function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >new element created dynamically yay!</p><button onclick="removeElement()">remove</button></div>'
);
}

function removeElement() {
alert('element removed dynamically boOoOoOoOooo!')
$('.newElem').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>

最佳答案

你可以这样做:

function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >new element created dynamically yay!</p><button onclick="removeElement(this)">remove</button></div>'
);
}

function removeElement(element) {
alert('element removed dynamically boOoOoOoOooo!')
$(element).parent(".newElem").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>

关于javascript - 如何动态删除javascript中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51012490/

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