【发布时间】:2012-02-27 17:59:30
【问题描述】:
我正在尝试在子菜单上使用显示/隐藏。它看起来像这样:
- 父 1
- 父 2
- 孩子A
- 孩子B
- 父 3
- 儿童C
- 儿童 D
我只想在单击其父级时显示子菜单。目前,每当我单击任何父级时,我都会获得所有子菜单。
像这样:http://jsfiddle.net/saltcod/z7Zgw/
此外,单击子菜单中的链接可切换菜单备份。
【问题讨论】:
我正在尝试在子菜单上使用显示/隐藏。它看起来像这样:
我只想在单击其父级时显示子菜单。目前,每当我单击任何父级时,我都会获得所有子菜单。
像这样: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')
您还可以停止在嵌套的.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.target 和this。
不过,这样更快:
$('.parent > li > a').click(function(){
event.preventDefault();
$(this).parent().find('.child').slideToggle('slow');
});
EDIT 正如@Jasper 指出的那样,这更短/更快:
$('.parent > li > a').click(function(){
event.preventDefault();
$(this).siblings('.child').slideToggle('slow');
});
【讨论】: