JQuery.toggle () to show and hide the submenu

I am trying to use show / hide in a submenu. It looks like this:

  • Parent 1
  • Parent 2
    • Child A
    • Child B
  • Parent 3
    • Baby c
    • Baby D

I want to show a submenu when I click on its parent. Currently, when I click on any parent, I get all the submenus.

So: http://jsfiddle.net/saltcod/z7Zgw/

In addition, clicking on the link in the submenu switches the backup menu.

+1
source share
2 answers
//select all the `<li>` element that are children of the `.parent` element $('.parent').children().click(function(){ //now find the `.child` elements that are direct children of the clicked `<li>` and toggle it into or out-of-view $(this).children('.child').slideToggle('slow'); }); 

Demo: http://jsfiddle.net/jasper/z7Zgw/1/

Basically, the code above uses this to refer to the clicked <li> element so that we can find the .child element, which is a child of the clicked <li> element.

This is: $('.child')

Changed to: $(this).children('.child')

Update

You can also stop the propagation of the click event on nested .child elements as follows:

 $('.parent').children().click(function(){ $(this).children('.child').slideToggle('slow'); //select all the `.child` elements and stop the propagation of click events on the elements }).children('.child').click(function (event) { event.stopPropagation(); }); 

Demo: http://jsfiddle.net/jasper/z7Zgw/9/

Docs:

+4
source

Your code:

 $('.parent li').click(function(){ event.preventDefault(); $('.child').slideToggle('slow'); }); 

$('.child') selects all the "children". Change it to $('.child', this) to select only those that are inside the current element.

click event templates, therefore, to ensure that only clicking on the parent element itself switches state, you can compare event.target with this .

However, this is faster:

 $('.parent > li > a').click(function(){ event.preventDefault(); $(this).parent().find('.child').slideToggle('slow'); }); 

See fiddle

EDIT , as @Jasper pointed out, this will be shorter / faster:

 $('.parent > li > a').click(function(){ event.preventDefault(); $(this).siblings('.child').slideToggle('slow'); }); 
+2
source

Source: https://habr.com/ru/post/1490557/


All Articles