如何隐藏在Jquery中没有点击并显示子菜单的ul? [英] How do I hide the ul's that are not clicked and show submenu in 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屋!