open sub menu onclick and close opened sub menu

空扰寡人 提交于 2019-12-24 14:06:06

问题


I'm using a JS code to dispay sub menu from menu by clicking on li items. when I click on a li item, when sub menu slideToggle and if a sub menu is already openned then it's slideUp. It works perfectly.

But I have juste one issue, when clicking on a li from my sub menu, it slideUp and then SlideToggle again, how can I prevent this ?

Here is my jquery :

$("#menu li").click(function () {
    $('ul.sub-menu').not( $(this).children() ).slideUp();
    $(this).children("ul.sub-menu").slideToggle();
});

and here is what I've tried so far without success :

$("#menu li").not($('#menu li sub-menu li a')).click(function () {
    $('ul.sub-menu').not( $(this).children() ).slideUp();
    $(this).children("ul.sub-menu").slideToggle();
});

here is my html :

<ul id="menu">
<li><a href="#">1</a></li>
<li>2
<ul class="sub-menu">
<li><a href="#">2.1</a></li>
<li><a href="#">2.2</a></li>
</ul> 
</li>
<li>3
<ul class="sub-menu">
<li><a href="#">3.1</a></li>
</ul> 
</li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">6</a></li>
</ul>

and my CSS :

.sub-menu {display:none}

and a Jsfiddle to see it in action :

http://jsfiddle.net/2s023cfc/1/

can anybody help me with this ? thanks


回答1:


Try This-

  $("#menu li").not($('#menu li sub-menu li a')).click(function (e) {
        $('ul.sub-menu').not( $(this).children() ).slideUp();
        $(this).children("ul.sub-menu").slideToggle();
        e.stopPropagation()
    });

You need to stop propagation.




回答2:


Specify the most to which element you are targeting the event in JQuery!

$("#menu > li > a").click(function () {
    $('ul.sub-menu').not($(this).siblings()).slideUp();
    $(this).siblings("ul.sub-menu").slideToggle();
});
.sub-menu {
    display:none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
    <li><a href="#">1</a></li>
    <li><a href="#">2</a>
        <ul class="sub-menu">
            <li><a href="#">2.1</a></li>
            <li><a href="#">2.2</a></li>
        </ul>
    </li>
    <li><a href="#">3</a>
        <ul class="sub-menu">
            <li><a href="#">3.1</a>
            </li>
        </ul>
    </li>
    <li><a href="#">4</a>
    </li>
    <li><a href="#">5</a>
    </li>
    <li><a href="#">6</a>
    </li>
</ul>


来源:https://stackoverflow.com/questions/31003519/open-sub-menu-onclick-and-close-opened-sub-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!