jQuery .toggle() to show and hide a sub-menu

后端 未结 2 1532
野性不改
野性不改 2020-12-20 06:04

I\'m trying to use show/hide on a submenu. It looks like this:

  1. Parent 1
  2. Parent 2
    1. Child A
    2. Child B
  3. Parent 3
相关标签:
2条回答
  • 2020-12-20 06:06
    //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 reference the clicked <li> element so we can find the .child element that is a child of the clicked <li> element.

    This: $('.child')

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

    Update

    Also you can stop the propagation of the click event on the nested .child elements like this:

    $('.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:

    • event.stopPropagation(): http://api.jquery.com/event.stopPropagation
    • .children(): http://api.jquery.com/children
    0 讨论(0)
  • 2020-12-20 06:25

    Your code was:

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

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

    The click event bubbles, so in order to ensure that only clicking the parent itself toggles the state, you can compare the event.target with this.

    However, this is quicker:

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

    See fiddle

    EDIT as @Jasper pointed out, this is shorter/quicker:

    $('.parent > li > a').click(function(){
        event.preventDefault();
        $(this).siblings('.child').slideToggle('slow');
    });
    
    0 讨论(0)
提交回复
热议问题