简体   繁体   English

JS Dropdown菜单没有关闭?

[英]JS Dropdown menu not closing?

So I found this fiddle here: http://jsfiddle.net/8qPvp/4/ I thought I'd use it just for personal education purposes. 所以我在这里找到了这个小提琴: http//jsfiddle.net/8qPvp/4/我以为我只是出于个人教育目的而使用它。 I'm really new with JS, and I noticed that the opened parent does not go back on click, like it opens. 我是JS的新手,我注意到打开的父级不会再次点击,就像它打开一样。 How could this be fixed? 怎么能修好?

$(document).ready(function () {
    $("li").click(function () {
        $('li > ul').hide();
        $(this).children("ul").toggle();
    });
});
$(document).ready(function () {
    $("li").click(function () {
        $('li > ul').hide();
        $(this).children("ul").toggle();
    }).mouseleave(function(){
        $(this).children("ul").hide();
    });
});

Check this fiddle http://jsfiddle.net/Aveendra/8qPvp/18/ 检查这个小提琴http://jsfiddle.net/Aveendra/8qPvp/18/

What about this: 那这个呢:

$("li").click(function () {
    $('li > ul').hide();
    $(this).children("ul").toggle();
});

$(document).click(function()
{
    $('li > ul:visible').hide();
})

$('.menu li').click(function(e)
{
    e.stopPropagation();          
})

So by default i make whenever there is clicked ANYWHERE in the document, your visible menu will be hidden. 因此,默认情况下,只要在文档中单击任何地方,我就会生成您的可见菜单。 However you don't want this to happen when you open a new menu(would be; made visible and made hiden directly). 但是,当您打开一个新菜单时,您不希望发生这种情况(将会显示为可见并直接隐藏)。 So i make a exception that catch when you want to open a new menu and i'll cancel the document click event. 所以当你想要打开一个新菜单并且我将取消文档点击事件时,我会抓住一个例外。
I use event.stopPropagation() to cancel a event. 我使用event.stopPropagation()来取消事件。

jsFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM