JQuery -- this 和 $(this) 的區別

起初以爲this和$(this)就是一模子刻出來。但是我在閱讀時,和coding時發現,總不是一回事。
[b]What is "this"?[/b]
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的好處是它包裝了各種瀏覽器版本對DOM對象的操作,因此統一使用$(this)而不再用this應該是比較不錯的選擇。

參考:http://remysharp.com/2007/04/12/jquerys-this-demystified/
發佈了188 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章