gpt4 book ai didi

javascript - 将div添加到html和数组中,如果删除,则需要将它们从html和数组中删除

转载 作者:行者123 更新时间:2023-11-30 06:50:04 25 4
gpt4 key购买 nike

我使用这段代码将一个 div 添加到我的 html 页面:

$('.block:last').after(
'<div class="block">' + blabla +
'<span class="remove"><button type="button"></button></span></div>'
)

我使用它是因为它在最后找到的 div> block 之后添加了一个带有 className Block 的新 div。

工作完美。但是在数组中也需要它,当然在删除的情况下也将它从数组中删除。

这是删除 div block 的代码(所有添加的 div 都在 div optionBox 中):

$('.optionBox').on('click','.remove',function() {
$(this).parent().remove();
});

删除 div 也很完美现在,如何将这些数据也放入数组中?

提前致谢

最佳答案

你可以这样做:

var $elementToAdd = $('<div class="block">' + blabla +
'<span class="remove"><button type="button"></button></span></div>');
yourArray.push($elementToAdd);
var indexInArray = yourArray.indexOf($elementToAdd);
$elementToAdd.data('index-in-array',indexInArray);
$('.block:last').after($elementToAdd);

并删除该元素:

$('.optionBox').on('click','.remove',function() {
yourArray.splice($(this).parent().data('index-in-array'),1);
$(this).parent().remove();
});

关于javascript - 将div添加到html和数组中,如果删除,则需要将它们从html和数组中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568465/

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