【发布时间】: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>
我想通过点击按钮只显示下一个兄弟<div class="prev-content">,但是有一些奇怪的行为。它显示所有 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