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

后端 未结 2 1537
野性不改
野性不改 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: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');
    });
    

提交回复
热议问题