简体   繁体   中英

JavaScript: Hide and Show Menu Class

var Menu = function() {
    state = 0;
}
Menu.prototype.click = function() {
    if (this.state == 1) {
        $(document).ready(function(){
            $("#collapse-menu").click(function(){
                $("#list-navbar").show(500);
                this.state = 0;
            });
        });
    } else {
        $(document).ready(function(){
            $("#collapse-menu").click(function(){
                $("#list-navbar").hide(500);
                this.state = 1;
            });
        });
    }
}

How can I instantiate the class on the page load and just call the function click onclick event, keeping the class instantiated?

var Menu = function() {
  this.state = 0;
};

Menu.prototype.click = function() {
  var that = this;   // our Menu object

  $("#collapse-menu").click(function(){
    that.state ^= 1; // Toggles 1,0,1... values
    $("#list-navbar")[that.state?"hide":"show"](500);
  });
};


jQuery(function( $ ) { // DOM ready here

  var m = new Menu();  // New Menu instance
  m.click();           // init clicks on #collapse-menu

});

jsBin demo

about ^ as toggler: https://stackoverflow.com/a/22061240/383904

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM