JavaScript:隐藏和显示菜单类

时间:2016-03-26 20:12:35

标签: javascript jquery 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;
            });
        });
    }
}

如何在页面加载上实例化类,只需调用函数click onclick事件,保持类实例化?

1 个答案:

答案 0 :(得分:2)

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

关于^ to toggler:https://stackoverflow.com/a/22061240/383904