What is "this"?
In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.
代碼如下:
$("#textbox").hover(
function() {
this.title = "Test";
},
fucntion() {
this.title = "OK”;
}
);
這里的this其實是一個Html 元素(textbox),textbox有text屬性,所以這樣寫是完全沒有什么問題的。
但是如果將this換成$(this)就不是那回事了,Error–報了。
Error Code:
代碼如下:
$("#textbox").hover(
function() {
$(this).title = "Test";
},
function() {
$(this).title = "OK";
}
);
這里的$(this)是一個JQuery對象,而jQuery對象沒有title 屬性,因此這樣寫是錯誤的。
JQuery擁有attr()方法可以get/set DOM對象的屬性,所以正確的寫法應該是這樣:
正確的代碼:
代碼如下:
$("#textbox").hover(
function() {
$(this).attr('title', ‘Test');
},
function() {
$(this).attr('title', ‘OK');
}
);
詳談jQuery中的this和$(this)
http://www.jb51.net/article/57376.htm