gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:38:01 25 4
gpt4 key购买 nike

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

  1. 父级 1
  2. 父级 2
    1. child A
    2. child B
  3. 家长 3
    1. 子C
    2. child 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/

文档:

关于jQuery .toggle() 显示和隐藏子菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9469807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com