【问题标题】:stop bubbling event onclick停止冒泡事件 onclick
【发布时间】:2021-03-11 11:12:05
【问题描述】:

我有以下

<p>haha</p>
<button class="btn btn-light" onclick="nextSibling.classList.toggle('d-none');">
  <i class="fa fa-ellipsis-h"></i>
</button>
<div class="prev-content d-none">
  <p>second reply from second account</p>
  <br>
  <button class="btn btn-light" onclick="nextSibling.classList.toggle('d-none');">
    <i class="fa fa-ellipsis-h"></i>
  </button>
  <div class="prev-content d-none">
    <p>reply from system</p>
  </div>
</div>

我想通过点击按钮只显示下一个兄弟&lt;div class="prev-content"&gt;,但是有一些奇怪的行为。它显示所有 div 或隐藏所有 div。我认为是冒泡事件的原因。

我该如何解决?

【问题讨论】:

  • PS:您应该始终根据肌肉记忆将type="button" 添加到所有非提交类型的按钮。
  • 另外,您的示例产生 "Uncaught TypeError: Cannot read property 'toggle' of undefined"
  • 对于初学者,您应该使用nextElementSibling 而不是nextSibling——因为在某些浏览器中,后者可能是指元素之间的空白 text 节点.
  • “我认为冒泡事件的原因。” - 即使事件从这些按钮元素冒泡,它们都没有任何祖先元素对点击事件做出反应.那么冒泡怎么可能负责呢?
  • 适用于nextElementSibling,请参阅jsfiddle.net/2dg64qzn/1

标签: javascript html bootstrap-4 event-bubbling


【解决方案1】:

const toggleNext = (ev) => {
  const EL = ev.currentTarget;
  const EL_next = EL.nextElementSibling;
  EL_next.classList.toggle("u-none");
};
const ELs_tog = document.querySelectorAll("[data-toggle-next]");
ELs_tog.forEach(EL => EL.addEventListener("click", toggleNext));
.u-none {display: none;}
<button type="button" data-toggle-next>TOGGLE</button>
<div class="u-none">
  <p>second reply from second account</p>
  <button type="button" data-toggle-next>TOGGLE</button>
  <div class="u-none">
    <p>reply from system</p>
  </div>
</div>

补充阅读:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2012-09-30
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2012-04-01
    相关资源
    最近更新 更多