您的代码相当于:
$("#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
})