あなたのコードは以下と同等です:
$("#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
})