我为应用程序中的每个 li
元素附加了 2 个按钮:
todoLi.appendChild(this.createToggleButton());
todoLi.appendChild(this.createDeleteButton());
后来,我添加了事件监听器,以便在鼠标悬停在 li
上时触发
todosUl.addEventListener('mouseover', function(event) {
let elementMousedOver = event.target;
if(elementMousedOver.className == 'todoLi') {
elementMousedOver.lastElementChild.style.display = 'inline';
}
});
todosUl.addEventListener('mouseout', function(event) {
let elementMousedOver = event.target;
if(elementMousedOver.className == 'todoLi') {
elementMousedOver.lastElementChild.style.display = 'none';
}
});
对于 li
元素来说一切正常,但是当我将鼠标悬停在作为 li 元素的子元素的按钮上时,如果按钮不是 li 元素的子元素,则事件监听器会由于某种原因停止工作全部。
如何使附加的子项也触发其父项的事件监听器?
这是我在 github 上的应用程序:https://mikestepanov.github.io/
包含文件的存储库:https://github.com/mikestepanov/mikestepanov.github.io
最佳答案
事件默认在 DOM 中冒泡,因此从 li 触发的事件也会触发 ul,问题是你的 if 语句只会处理事件目标是 ul 的情况(className == “todoLi”)
var todosUl = document.getElementsByClassName("todo")[0];
todosUl.addEventListener('mouseover', function(event) {
let eOver = event.target;
if(eOver.className == 'todo') {
//for the ul
console.log("I'm handeled from " + eOver.className);
} else if (eOver.className == 'item') {
//for the li
console.log("I'm handeled from " + eOver.className);
}
});
todosUl.addEventListener('mouseout', function(event) {
let eOver = event.target;
if(eOver.className == 'todo') {
//for the ul
console.log("I'm handeled from " + eOver.className);
} else if (eOver.className == 'item') {
//for the li
console.log("I'm handeled from " + eOver.className);
}
});
ul{
padding: 15px;
background: lightblue;
}
li{
background: grey;
padding: 5px 5px;
}
<ul class="todo">
<li class="item">Do it!!</li>
</ul>
关于javascript - 使附加的子元素也触发父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47491539/