Jquery: Show/hide menu with single button

2019-03-06 09:00发布

问题:

I am trying to make a button that calls a menu. After the menu has been called, clicking on the button should close the menu.

There are also some classes that should be added to the menu/button to assist with styling.

How can I do this? (I am using jQuery 1.8.3.)

This is my code:

$(function() {
    "use strict";
    $(document).on('click', '.anchor', function() {

        $('.ui-tapmenu').removeClass("animated bounceInDown");
        $('.ui-tapmenu').hide();
        $('.overlay').hide();
        var menuId = $(this).data('menu');
        var menuName = '.' + menuId;
        $(".loading").delay(1000).show(0);
        $(menuName).addClass("animated bounceInDown");
        $(menuName).show();
        $(this).addClass('close jq-close');
    });

    $('body').on('click', '.close', function() {
        $(this).addClass('anchor');
        $(this).removeClass('close');
        $('.ui-tapmenu').removeClass("animated bounceInDown");
        $('.ui-tapmenu').hide();
        $('.overlay').hide();
        $('.anchor.jq-close').removeClass('close');
    });

});

JS Fiddle: http://jsfiddle.net/big_smile/d4ajx/

Problem: it works, but when the menu is closed, the open code refires, so the menu stays permanently open. I am not sure why this happens, as when the "open code" runs it adds a class to the trigger. The "close code" only works on this class, so the "open code" shouldn't run again.

Here is another version:

$(function() {
    "use strict";
    $(document).on('click', '.anchor', function() {

        $('.ui-tapmenu').toggleClass("animated bounceInDown");
        $('.ui-tapmenu').toggle();
        $('.overlay').toggle();
        var menuId = $(this).data('menu');
        var menuName = '.' + menuId;
        $(".loading").delay(1000).toggle(0);
        $(menuName).toggleClass("animated bounceInDown");
        $(menuName).toggle();
        $(this).toggleClass('close jq-close');
    });

});

JsFiddle: http://jsfiddle.net/big_smile/G48bK/

Problem: This uses toggle. The menu is initially hidden with CSS. Toggle sets the menu to"display:none" and then never sets it to "display:block".

回答1:

When you click on an element, the click event is triggered and it bubbles up to all containing elements. Both the body and the document will receive this event.

To fix your code, you need to listen from the same place.

Just change $(document) to $('body').

JSFiddle: http://jsfiddle.net/d4ajx/1/

See this diagram for more information.