jQuery .toggle()显示和隐藏子菜单 [英] jQuery .toggle() to show and hide a sub-menu

查看:73
本文介绍了jQuery .toggle()显示和隐藏子菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use show/hide on a submenu. It looks like this:

  1. 父母1
  2. 父母2
  1. 孩子A
  2. 孩子B

  • 父母3

  • Parent 3

    1. 孩子C
    2. 孩子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

    这篇关于jQuery .toggle()显示和隐藏子菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆