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

╄→尐↘猪︶ㄣ 提交于 2019-12-08 02:56:27

问题


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.



来源:https://stackoverflow.com/questions/11883663/jquery-link-doesnt-work-after-toggle

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