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

2019-09-06 02:18发布

问题:

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?