您的代码就相当于:
$("#clickme").on("click", function(){
alert(this.innerHTML); // `this` points to the event object (`section`)
window.setTimeout(function(){ // notice the 'window.'
alert(this.innerHTML); // `this` now points to `window`
}, 1000);
})
的undefined
错误来,因为this.innerHTML
转化为window.innerHTML
因为内部this
点window
。 window
对象没有innerHTML
属性,因此它会导致undefined
属性。
为了使用section
元素对象,你需要它缓存在一个变量的地方:
$("#clickme").on("click", function(){
var _this = this; // cached
alert(_this.innerHTML); // use cached
setTimeout(function(){
alert(_this.innerHTML); // use cached
}, 1000);
})
或者,我不知道会在IE是工作的方法把它作为一个参数为setTimeout
:
$("#clickme").on("click", function(){
alert(this.innerHTML); // `this` points to the event object (`section`)
setTimeout(function(_this){ // notice the `_this` as a parameter
alert(_this.innerHTML); // `_this` now points to the argument
}, 1000, this); // pass it here
})
但为什么它给了我一个未定义的结果? –
@PenghanYang:因为在'setTimeout'处理程序中,'this'是'window'(因为'setTimeout'实际上是'window.setTimeout');所以'this.innerHTML'是'window.innerHTML',这不是你想要的。 – Amadan
@彭汉阳,这里有很多关于javascript上下文的参考资料[了解Javascript上下文](http://joshuakehn.com/2011/10/20 /Understanding-JavaScript-Context.html)和[Javascript this different contexts](http://www.impr essivewebs。com/javascript-this-different-contexts /) – smerny