0

我正在开发一个 jquery 插件,我正在使用这个样板jqueryboilerplate,我的插件被称为 textarea,我正在调用这样的按键事件

init: function(){
  $(this.element).keypress(function(){
    alert('hey');
  });
},

所以这个警报工作正常,所以在按键内他看不到我的本地方法。

init: function(){
  $(this.element).keypress(function(){
    this.sayHey();
  });
},
sayHey:function(){
  alert('hey');
}
4

2 回答 2

1

另一种解决方案是使用$.proxy将自定义上下文传递给事件回调函数

init: function(){
    $(this.element).keypress($.proxy(function(){
        this.sayHey();
    }, this));
},
sayHey:function(){
    alert('hey');
}

或者更好的是这里不需要创建匿名函数

init: function(){
    $(this.element).keypress($.proxy(this.sayHey, this));
},
sayHey:function(){
    alert('hey');
}
于 2013-07-04T04:23:51.477 回答
0

在按键回调中, 的值this不再引用您的插件对象。尝试使用这样的that技巧:

init: function(){
  var that = this;
  $(this.element).keypress(function(){
    that.sayHey();
  });
},
sayHey:function(){
  alert('hey');
}
于 2013-07-04T04:05:54.137 回答