javascript - 使附加的子元素也触发父元素

标签 javascript

我为应用程序中的每个 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/

相关文章:

javascript - 如何将数据从 POST 请求传递到对外部服务的请求?

java - 在 Lotus Notes 中自动发送邮件

c# - 查找aspx页面中存在的所有控件和子控件id以及相应的ascx用户控件

javascript - 使用 Window_handles 单击位置弹出窗口中的按钮,带守夜人

javascript - 试图让图像完全重叠,同时依次淡入

javascript - 从元素获取值并添加到每个 href 的末尾

javascript - 使用 jQuery 遍历父树

javascript - 当面板ID动态生成时,点击时如何获取面板的ID

javascript - 在将函数作为参数传递给 jquery 委托(delegate)事件处理程序时尝试使用 "this"而不必使用 "that"

javascript - php和js重定向错误