简体   繁体   English

事件.stopPropagation(); 没有按预期表现

[英]event.stopPropagation(); doesn't behave as expected

I read couple articles related to event.stopPropagation();我阅读了与event.stopPropagation(); but none of the solutions provided works for me.但是提供的解决方案都不适合我。 Basically what I have is an accordion widget with all the elements collapsed by default.基本上我所拥有的是一个默认折叠所有元素的手风琴小部件。 On each element header (dt tag) there is also a checkbox.在每个元素 header(dt 标签)上还有一个复选框。 Clicking the checkbox shouldn't trigger the accordion to make its elements expand.单击复选框不应触发手风琴以使其元素展开。

<dt data-toggle="collapse">
<span class="subscribe-checkbox"><button type="button" class="btn toggle-btn" data-toggle="button"></button></span>
</dt>
<dd>
<p>Accordion content...</p>
</dd>

Clicking the span (which should act as a checkbox) should add class "checked" to it.单击跨度(应充当复选框)应向其添加 class“选中”。 However it also expands the accordion element (dd tag).然而,它也扩展了手风琴元素(dd 标签)。 What I'm doing in jQuery is:我在 jQuery 中所做的是:

$('.accordion-group .btn.toggle-btn').click(function (event) {
event.stopPropagation();
});

While the accordion content isn't shown (which is good) the <span> element doesn't change class either, so it doesn't become 'checked'.虽然未显示手风琴内容(这很好),但<span>元素也不会更改 class,因此它不会变为“已选中”。 I tried with .live() too and didn't work either.我也试过.live()也没有用。

You have to use addEventListener and then use the boolean Capture argument to control the behaviour of parent elements.您必须使用addEventListener ,然后使用 boolean Capture参数来控制父元素的行为。

stopPropagation() does not work because the <dd> is not a parent to the <span> , so the event does not propagate from the <span> to the <dd> . stopPropagation() 不起作用,因为<dd>不是<span>的父级,因此事件不会从<span>传播到<dd>

You'll have to restructure the handlers a little bit, maybe remove the click handler for the parent element of this whole code, and add a new handler for the <dd>您必须稍微重组处理程序,也许删除整个代码的父元素的点击处理程序,并为<dd>添加一个新的处理程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM