简体   繁体   中英

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

I read couple articles related to 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. 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. However it also expands the accordion element (dd tag). What I'm doing in jQuery is:

$('.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'. I tried with .live() too and didn't work either.

You have to use addEventListener and then use the boolean Capture argument to control the behaviour of parent elements.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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