我有以下代码:
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" />
元素。我需要编写一些方法来增强按键事件。
如何获取对其中对象实例的引用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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)