使用addeventListener附加事件时,为什么不发生事件冒泡

时间:2019-02-13 09:02:05

标签: javascript

在以下代码中,使用addEventListener将click事件附加到每个p元素。由于click事件是附加到每个父元素或嵌套p元素的,因此我希望由于事件冒泡,在子p上单击也会触发父p的附加点击事件。但是那不会发生。

是否使用addEventListener附加事件,该事件在默认情况下不会冒泡(传播)?

var content = document.getElementsByTagName('p');
for (idx = 0; idx < content.length; idx++) {
  content[idx].addEventListener('click', function() {
    alert(this.parentNode.classList)
  }, false)
}
.ancestor p {
  border: 1px solid red;
  width: 200px;
  background-color: yellow;
}

.parent>p {
  background-color: blue
}

.child p {
  margin: 0;
  background-color: grey;
}
<body>
  <div class="ancestor">
    <p>Ancestor Pargraph</p>
    <div class="parent">
      <p>Parent Paragraph</p>
      <div class="child" tabindex='2'>
        <p>Child Paragraph</p>
      </div>
    </div>
  </div>
</body>

谢谢。

1 个答案:

答案 0 :(得分:0)

事件冒泡触发的是祖先而不是祖先的孩子

<p>不是任何事物的父母。每次点击<p>都会冒出一个父div(没有监听器,然后冒出另一个div(没有监听器)),并绕过该div的子对象<p>,依此类推。冒泡会传给下一个祖先,而不是祖先的孩子。

在下面的演示中,每个<div>都有一个eventListener()。每个<div>都是父项(与<p>不同),您会看到事件冒泡有效。


演示

var content = document.getElementsByTagName('div');
for (idx = 0; idx < content.length; idx++) {
  content[idx].addEventListener('click', function() {
    alert(this.classList)
  }, false)
}
.ancestor p {
  border: 1px solid red;
  width: 200px;
  background-color: yellow;
}

.parent>p {
  background-color: blue
}

.child p {
  margin: 0;
  background-color: grey;
}
<body>
  <div class="ancestor">
    <p>Ancestor Pargraph</p>
    <div class="parent">
      <p>Parent Paragraph</p>
      <div class="child" tabindex='2'>
        <p>Child Paragraph</p>
      </div>
    </div>
  </div>
</body>