如何隐藏未单击的ul并在Jquery中显示子菜单?

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

除了点击的列表外,我怎样才能打开它?

// 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"); } }); 

这是因为当您单击子菜单时,将针对单击的li和父li激发该事件。 调用stopPropagation会阻止这种情况。

此外,当您点击子li时,您可以向上滑动除了单击的li之外的所有li,这也会向父级滑动。 更改.not语句以排除目标和所有父项。

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

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