jQuery .toggle()显示和隐藏子菜单 [英] jQuery .toggle() to show and hide a sub-menu
问题描述
我正在尝试在子菜单上使用显示/隐藏.看起来像这样:
I'm trying to use show/hide on a submenu. It looks like this:
- 父母1
- 父母2
- 孩子A
- 孩子B
- 孩子C
- 孩子D
我只想在单击子菜单的父菜单时显示该子菜单.当前,每当我单击任何父项时,我都会获得所有子菜单.
I only want to show the submenu when I click on its parent. Currently, whenever I click on any parent, I get all of the submenus.
例如: http://jsfiddle.net/saltcod/z7Zgw/
此外,单击子菜单中的链接可以切换菜单.
Also, clicking on a link in the submenu toggles the menu back up.
推荐答案
//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>
元素,因此我们可以找到作为被单击的<li>
元素的子元素的.child
元素.
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.
此:$('.child')
更改为:$(this).children('.child')
您还可以像这样在嵌套的.child
元素上停止传播click
事件:
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();
});
演示: http://jsfiddle.net/jasper/z7Zgw/9/
文档:
-
event.stopPropagation()
: http://api.jquery.com/event.stopPropagation -
.children()
: http://api.jquery.com/children
event.stopPropagation()
: http://api.jquery.com/event.stopPropagation.children()
: http://api.jquery.com/children
这篇关于jQuery .toggle()显示和隐藏子菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!