如何隐藏在Jquery中没有点击并显示子菜单的ul? [英] How do I hide the ul's that are not clicked and show submenu in Jquery?

查看:166
本文介绍了如何隐藏在Jquery中没有点击并显示子菜单的ul?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用html列表的下拉菜单。 jquery代码在第一级工作正常,但是当我尝试点击列表中的某个子菜单时,它会关闭并重新打开相同的列表。



我如何获得它打开除了我点击的列表之外的所有东西?

  //文档听力
$(document).ready (){

// JQuery运行正常,不需要CSS技巧下载
//删除子孙的类,这将删除CSS'falback'
$(#nav ul.child)。removeClass(child);
$(#nav ul.grandchild)。removeClass(grandchild);

//当
$(#nav li)上有一个包含无序列表的列表项时,会有(ul)点击(function(e){
$(#nav li ).children(ul)。not(e.target).slideUp(fast);
$(this).children(ul)。slideDown(fast);
});

});

//文档单击
//单击其他任何其他其他链接,然后单击并关闭
$(document).mouseup(function(event){
如果(!$(event.target).closest(#nav li)。length){
$(#nav li)。children(ul)。slideUp(fast);
}
});


解决方案

这是因为当您点击子菜单时,对于点击的li和父级li都会触发该事件。调用stopPropagation将会阻止。



此外,当您点击孩子li时,您可以向上滑动所有的李,而不是点击的李,这也向上滑过父母。更改.not语句以排除目标和所有父母。

  $(#nav li)。 ).click(function(e){
$(#nav li)。children(ul)。not($(this).parents())。slideUp(fast);
$(this).children(ul)。slideDown(fast);
e.stopPropagation();
});

这是一个工作小提琴:
http://jsfiddle.net/qnzsS/1/


I have a dropdown menu using a html list. The jquery code works fine at the first level, but when i try to click something on the list with a submenu it closes and reopens the same list.

How can I get it to open everything but the list i clicked?

    // Document Listening
$(document).ready(function () {

    // JQuery running fine, don't need CSS trick for dropdown
    // Remove the class of child and grandchild, this removes the CSS 'falback'
    $("#nav ul.child").removeClass("child");
    $("#nav ul.grandchild").removeClass("grandchild");

    // When a list item that contains an unordered list is hovered on
    $("#nav li").has("ul").click(function (e) {
        $("#nav li").children("ul").not(e.target).slideUp("fast");
        $(this).children("ul").slideDown("fast");
    });

});

// Document Click 
// Click on anything else other then the link you clicked and close
$(document).mouseup(function (event) {
    if (!$(event.target).closest("#nav li").length) {
        $("#nav li").children("ul").slideUp("fast");
    }
});

解决方案

This is caused because when you click on a submenu, the event is fired for both the clicked li and the parent li. Calling stopPropagation will prevent that.

In addition, when you click on a child li, you slide up all li's other than the clicked li, which also slides up the parent. Change the .not statement to exclude the target and all parents.

$("#nav li").has("ul").click(function (e) {
    $("#nav li").children("ul").not($(this).parents()).slideUp("fast");
    $(this).children("ul").slideDown("fast");
    e.stopPropagation();
});

Here's a working fiddle: http://jsfiddle.net/qnzsS/1/

这篇关于如何隐藏在Jquery中没有点击并显示子菜单的ul?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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