使附加子元素也触发父元素

用户8929940

我为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';
  }
});

对于lielement来说,一切正常,但是当我将鼠标悬停在按钮上(属于li元素的子代)时,如果bottons毕竟不是li element的子代,则事件侦听器由于某种原因会停止工作。

如何让附加的孩子也触发其父母的事件监听器?

这是我在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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章