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



我正在尝试在子菜单上使用显示/隐藏。它看起来像这样:

  1. 父级1
  2. 家长2
    1. 儿童A
    2. 儿童B
  3. 家长3
    1. 儿童C
    2. 儿童D

我只想在单击子菜单的父菜单时显示它。目前,每当我点击任何父菜单时,我都会得到所有的子菜单。

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

此外,单击子菜单中的链接可将菜单切换回上一级。

//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');     
});

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

基本上,上面的代码使用this来引用单击的<li>元素,因此我们可以找到.child元素,它是单击的<li>元素的子元素。

此: $('.child')

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

更新

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

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

最新更新