Using jQuery .on() to make a drop-down menu

五迷三道 提交于 2019-12-13 21:36:34

问题


I'm trying to make a jQuery drop down menu, that adds a class to know if it's down or up. But for some reason the .on() function doesn't seem to respond to clicks. What are I doing wrong?

Here is my HTML:

<ul id="main-menu" class="menu">
    <li>
        <a href="http://example.com">Item 1</a>
    </li>
    <li class="drop-down">
        <a href="http://example.com">Item 2</a>
        <ul class="sub-menu">
            <li>
               <a href="http://example.com">Sub Item 1</a>
            </li>
            <li>
               <a href="http://example.com">Sub Item 2</a>
            </li>
            <li>
               <a href="http://example.com">Sub Item 3</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="http://example.com">Item 3</a>
    </li>
</ul>

And my JS:

// Slide down
jQuery('#main-menu > li.drop-down > a').not('.active a').click(function(e){
    e.preventDefault();
    jQuery(this).closest('li.drop-down').addClass('active').find('ul.sub-menu').slideDown();
});

// Slide up
jQuery('#main-menu > li.drop-down.active > a').on('click', function(e){
    e.preventDefault();
    jQuery(this).closest('li.drop-down').find('ul.sub-menu').slideUp(400, function(){
        jQuery(this).closest('li.drop-down.active').removeClass('active');
    });
});

Thanks!


回答1:


You don't need 2 handlers for what you are trying to achieve.

You can just use one handler making use of toggleClass and slideToggle jQuery methods.

// Slide down
jQuery('#main-menu').on('click', 'li.drop-down > a', function(e){
    e.preventDefault();
    jQuery(this)
    .closest('li.drop-down')
    .toggleClass('active')
    .find('ul.sub-menu')
    .slideToggle(400, function(){
         if($(this).is(':hidden')){
              jQuery(this).closest('li.drop-down.active').removeClass('active');
         }
    });
});

References: .toggleClass(), .slideToggle()




回答2:


Why not use Superfish plugin?



来源:https://stackoverflow.com/questions/9268098/using-jquery-on-to-make-a-drop-down-menu

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