【发布时间】:2021-10-06 14:09:41
【问题描述】:
数组中有 5 个项目(其中包含对象),它通过根据数组长度在文档中创建一些元素来直观地表示。 像这样:
let array = [
{
"value": "Hello"
},
{
"value": "World"
},
{
"value": "You Can"
},
{
"value": " NOT"
},
{
"value": "<h1>Remove ME!</h1>"
}
]
// creating it visually by creating elements.
for(let i = 0; i < array.length; i++) {
const div = document.createElement("div");
div.classList.add("DIV");
div.innerHTML = `
<span class="Text">${array[i].value}</span>
<span class="Remove">( Remove )</span>
`
document.body.appendChild(div);
}
document.querySelectorAll(".Remove").forEach(elem => {
elem.addEventListener("click", () => {
remove();
})
})
function remove() {
// Now how to remove the specific item from the array?
}
// I hope this is fully understandable.
/* CSS IS NOT VERY IMPORTANT */
.DIV {
padding: 10px;
margin: 10px;
background: purple;
color: #fff;
border-radius: 10px;
display: flex;
justify-content: space-between;
}
.Remove {
cursor: pointer;
height: fit-content;
}
现在我想通过单击第 4 个删除按钮来删除数组中值为“NOT”的第 4 个元素,但我该怎么做。
(您的代码应该适用于所有元素。)
我们将不胜感激。谢谢。
【问题讨论】:
-
当你有动态元素时,最好对每个元素使用事件委托而不是监听器。为动态元素创建一个包装器,在包装器上监听点击,检查被点击元素的类名,然后移除其父级。
标签: javascript arrays dom-manipulation