Javascript 按键事件中的调用方法
我是一个jquery插件开发人员,我正在使用这个样板文件,我的插件被引用到textarea,我调用keypress事件就是这样Javascript 按键事件中的调用方法,javascript,jquery,jquery-plugins,this,Javascript,Jquery,Jquery Plugins,This,我是一个jquery插件开发人员,我正在使用这个样板文件,我的插件被引用到textarea,我调用keypress事件就是这样 init: function(){ $(this.element).keypress(function(){ alert('hey'); }); }, 所以这个警报工作正常,所以在按键中他看不到我的本地方法 init: function(){ $(this.element).keypress(function(){ this.sayHey(
init: function(){
$(this.element).keypress(function(){
alert('hey');
});
},
所以这个警报工作正常,所以在按键中他看不到我的本地方法
init: function(){
$(this.element).keypress(function(){
this.sayHey();
});
},
sayHey:function(){
alert('hey');
}
在按键回调中,
this
的值不再引用插件对象。试着使用那种
技巧,如下所示:
init: function(){
var that = this;
$(this.element).keypress(function(){
that.sayHey();
});
},
sayHey:function(){
alert('hey');
}
另一种解决方案是使用将自定义上下文传递给事件回调函数
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');
}