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

2019-09-06 01:40发布

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!

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-06 02:19

Why not use Superfish plugin?

查看更多
做个烂人
3楼-- · 2019-09-06 02:33

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()

查看更多
登录 后发表回答