gpt4 book ai didi

javascript - 在不删除关联事件的情况下从节点中删除元素?

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

我一直在从事 html/css/javascript 的“etch-a-sketch”风格的元素。简而言之,我有一个带有 mouseenter 事件的 div 元素网格:

const fillInGrid = document.querySelectorAll(".gridSquares");
fillInGrid.forEach((div) => {
div.addEventListener('mouseenter', (e) => {
div.style.backgroundColor = 'black';
});
});

在元素中,我有一个重置按钮,它从网格中删除子元素并用新的 div 替换它们,两个提示,其中用户指定了一些行和列,然后生成一个新的网格:

const resetButton = document.querySelector("#reset");
resetButton.addEventListener('click', (e) => {
const resetEvent = document.getElementById('container');
while (resetEvent.lastElementChild) {
resetEvent.removeChild(resetEvent.lastElementChild);
};
newGrid();
}
);

但是,在单击重置并为新网格选择尺寸后,生成了网格,但网格失去了对 mouseenter 事件的响应,因为我假设该事件与 div 一起被删除,有没有办法重新- 添加事件或替代方法,可以在没有关联事件的情况下删除 div?

演示该问题的代码笔链接:https://codepen.io/MaBuCode/pen/eYpjwOV

最佳答案

您可以在包含元素上添加一个事件监听器,而不是在子元素上添加多个事件监听器。这样,您的代码将变得更加高效,并且您还可以捕获在动态(新创建的)元素上触发的任何事件。

您需要将 mouseenter 事件替换为支持 bubblingmouseover 事件.

下面是添加和替换 mouseenter 事件的代码:

// // One event listener to rule them all:
document.getElementById("container").addEventListener('mouseover', (e)=>{

if ( e.target.classList.contains('gridSquares')){
e.target.style.backgroundColor = 'black';
}

});

您现在可以摆脱单独的 div 事件监听器:

fillInGrid.forEach((div) => {
div.addEventListener('mouseenter', (e) => {
div.style.backgroundColor = 'black';
});
});

Codepen Demo


提示:我还重构了“gridCreator”函数以减少 appendChild 操作的数量,并将其替换为简单的字符串连接以提高代码的性能:

function gridCreator(gridSize) {
let content = "";
for (let i = 0; i < gridSize; i++) {
content += "<div class='gridSquares'></div>";
}
document.getElementById("container").innerHTML = content;
}

通过上述方法,您还可以省略 resetButton 代码中删除 .container 子元素的代码。

关于javascript - 在不删除关联事件的情况下从节点中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61993286/

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