+ -
当前位置:首页 → 问答吧 → jquery插件给元素绑定方法的疑问

jquery插件给元素绑定方法的疑问

时间:2011-09-26

来源:互联网

在插件中 绑定给元素绑定方法的话, 直接调用, 插件中的方法,为啥提示,未定义方法呢
比如:
  1. (function($) {
  2. this.inits = function(){
  3. $("#message_close").click( function() {
  4. this.close(); // 这样调用提示 未定义方法
  5. });
  6. }

  7. this.close = function() {
  8. //xxxxxxxxxxx
  9. }
  10. })(jQuery);
复制代码

请教大家了, 有知道的帮忙给说一下原因了

作者: likun_power   发布时间: 2011-09-26

(function($) {
    this.inits = function(){
       $("#message_close").click( function() {
          this.close(); // 这样调用提示未定义方法:这里的this是$('#message_close');
        });
    }
    this.close = function() {
       //xxxxxxxxxxx
    }
})(jQuery);

这么写试试,我也没测试:

(function($) {
    var _this = this;
    this.inits = function(){
       $("#message_close").click( function() {
          _this.close();
       });
    }
    this.close = function() {
       //xxxxxxxxxxx
    }
})(jQuery);

作者: 2008futao   发布时间: 2011-09-26