我正试图在子菜单上使用show / hide.它看起来像这样:
>父母1
>父母2
>孩子A.
>孩子B.
>家长3
>孩子C.
>孩子D.
我只想在点击其父级时显示子菜单.目前,每当我点击任何父母时,我都会获得所有子菜单.
解决方法
//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/
基本上上面的代码使用它来引用点击的< 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