jQuery: link doesn't work after .toggle()

2019-05-26 08:34发布

问题:

I've just build a dropdown menu which I would like to drop down on a click, and go back up after an other click. This perfectly works with a toggle I have used, but the problem is that after the dropdown, the links don't execute.

$(function() {

    $("#nav_menu-2 ul.menu ul").css({ display: 'none' });


    $("#nav_menu-2 ul.menu #testbutton").toggle(function() {


        $(this).find('ul.sub-menu')
            .stop(true, true).delay(50).animate({ "height": "show", "opacity": "show" }, 300 );
    }, function(){

        $(this).find('ul.sub-menu')
            .stop(true, true).delay(50).animate({ "height": "hide", "opacity": "hide" }, 300 );
    });

});

So my geuss is that after the menu has dropped, it goes back up on a click, instead of executing the link. But since I'm quite new to javascript/jQuery, I have no idea what other option I have. Any ideas?

回答1:

I would instead use slideToggle, bound to the click event of the button that should open the menu:

$("#nav_menu-2 ul.menu #testbutton").click(function() {
  $('ul.sub-menu').slideToggle();
});

You might have to change the selectors slightly depending how your menu is constructed.



回答2:

This is a known side-effect of toggle(). The documentation says:

The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

To work around that, you will have to bind to click instead of toggle. As Andrew says, you can use slideToggle() to obtain the same behavior from a click event.