简体   繁体   中英

Why jQuery children selector is targeting the parent?

I'm working on a navigation bar that displays a dropdown menu on click. The script simply toggles the class to display it.

$(".dropdown-btn").click(function() {
  $(this).children(".dropdown").toggleClass("expanded");
});

Adding the styles, it works.

.dropdown {
    display: none;
}

.dropdown.expanded {
    display: block;
}

The problem comes when I add a nested dropdown menu. When I click on the nested ".dropdown-btn", the script toggles the class of the child dropdown (as it's supposed to) but it also toggles the class of the parent! To better explain what I mean, inspect the fiddle here: http://jsfiddle.net/3rm3ny1j/

I have two questions. What is the reason of this behavior? What is the best solution?

Because a click event will bubble up the DOM and trigger the click event on its ancestors.

Add .stopPropagation() and you can prevent that:

$(".dropdown-btn").click(function (e) {
    e.stopPropagation();
    $(this).children(".dropdown").toggleClass("expanded");
});

jsFiddle example

Your .dropdown is nested inside a .dropdown-btn causing any further clicks to trigger the parent event.

By separating the trigger and the dropdown you can stop them triggering upwards.

See this updated fiddle: http://jsfiddle.net/3rm3ny1j/2/

You have nested .dropdown-btn elements, and you don't stopPropagation , so clicking on one also clicks on all its ancestors.

NB: In order to answer this I had to follow a link to an external site so I could see all of your problem. Stackoverflow questions should stand on their own merits. SO even has snipit functionality now which does the same job as JSFiddle but locally.

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