微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

停止冒泡事件 onclick

如何解决停止冒泡事件 onclick

我有以下内容

<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>

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

我该如何解决

解决方法

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>

补充阅读:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。