首页 > 解决方案 > JQuery 模块模式:单击切换功能无法使用

问题描述

当我尝试访问方法“dropDownUserInfo”时单击它会给出错误[无法读取未定义的属性'slideToggle']

代码:

(function(){
var homePage = {
        init: function(){
            this.cacheDom();
            this.bindEvent();
        },            
        cacheDom: function(){
            this.$userInfo = $('.user-info a');
            this.$userContent = $('.user-info-content');
        },
        bindEvent: function(){                
            this.$userInfo.on('click', this.dropDownUserInfo);
        },
        dropDownUserInfo: function(){                                                                                                                     
            this.$userContent.slideToggle(500);
            this.$userInfo.toggleClass('active');   
       },          
    }
    homePage.init();
})();

标签: javascriptjquery

解决方案


this在事件处理方法dropDownUserInfo函数中,将引用引发事件的 DOM 元素。

你可以使用Function.bind()它来设置它的上下文。

this.$userInfo.on('click', this.dropDownUserInfo.bind(this));

这是一个例子

(function() {
  var homePage = {
    init: function() {
      this.cacheDom();
      this.bindEvent();
    },
    cacheDom: function() {
      this.$button = $('button');
    },
    bindEvent: function() {
      this.$button.on('click', this.buttonClick.bind(this));
      this.$button.on('click', this.buttonClick2);
    },
    buttonClick: function() {
      this.$button.toggleClass('active');
    },
    buttonClick2: function() {
      console.clear();
      this.$button.text('active'); //Will throw error
    }
  }
  homePage.init();
})();
.active {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button">Click Me</button>


推荐阅读