事件处理程序内的访问对象实例 [英] Access object instance inside an event handler
本文介绍了事件处理程序内的访问对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
var myObj = {
inputs: document.getElementsByTagName('input'),
attachKeyEvent: function() {
for ( var i = 0; i < this.inputs.length; i++ ) {
this.inputs[i].onkeypress = this.getChar;
console.log(this); // => returns ref to myObj
}
},
getChar: function(e) {
console.log(this); // => [Object HTMLInputElement]
// get a reference to myObj
}
}
我有一个DOM结构,其中有几个< input type =text/>
元素。我需要编写几种方法来增强按键事件。
I have a DOM structure with a couple of <input type="text" />
elements. I need to write a couple of methods to enhance the key press event.
如何获取中的对象实例的引用getChar()
?
推荐答案
像这样...
var myObj = {
inputs: document.getElementsByTagName('input'),
attachKeyEvent: function() {
var me = this;
var handler = function(){
me.getChar.apply(me, arguments);
}
for ( var i = 0; i < this.inputs.length; i++ ) {
this.inputs[i].onkeypress = handler;
console.log(this); // => returns ref to myObj
}
},
getChar: function(e) {
console.log(this); // => [Object HTMLInputElement]
// get a reference to myObj
}
}
这篇关于事件处理程序内的访问对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文