jQuery .toggle()显示和隐藏子菜单

我正试图在子菜单上使用show / hide。 它看起来像这样:

  1. 家长1
  2. 家长2
    1. 孩子A.
    2. 孩子B.
  3. 家长3
    1. 孩子C.
    2. 孩子D.

我只想在点击其父级时显示子菜单。 目前,每当我点击任何父母时,我都会获得所有子菜单。

像这样: http : //jsfiddle.net/saltcod/z7Zgw/

此外,单击子菜单中的链接可以切换菜单。

//select all the `
  • ` element that are children of the `.parent` element $('.parent').children().click(function(){ //now find the `.child` elements that are direct children of the clicked `
  • ` and toggle it into or out-of-view $(this).children('.child').slideToggle('slow'); });
  • 演示: http : //jsfiddle.net/jasper/z7Zgw/1/

    基本上上面的代码使用this来引用单击的

  • 元素,这样我们就可以找到.child元素,它是被点击的

  • 元素的子元素。

    这: $('.child')

    更改为: $(this).children('.child')

    更新

    您也可以停止在嵌套的.child元素上传播click事件,如下所示:

     $('.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(); }); 

    演示: http : //jsfiddle.net/jasper/z7Zgw/9/

    文档:

    • event.stopPropagation() : http : //api.jquery.com/event.stopPropagation
    • .children() : http : //api.jquery.com/children

    你的代码是:

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

    $('.child')选择所有“孩子”。 将其更改为$('.child', this) ,仅选择当前元素中的那些。

    click事件会冒泡,因此为了确保只单击父本身切换状态,您可以将event.targetthis进行比较。

    但是,这更快:

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

    看小提琴

    编辑为@Jasper指出,这更短/更快:

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