如何解决停止冒泡事件 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。我认为冒泡事件的原因。
我该如何解决?
解决方法
- 不要使用内联 JS,就像不要使用内联
style
属性 - 使用addEventListener
- 在函数处理程序中使用 Event.currentTarget 来引用事件委托元素
- 使用nextElementSibling
- 使用 finally classList.toggle 切换特定类
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 举报,一经查实,本站将立刻删除。