DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> JQuery this 和 $(this) 的區別
JQuery this 和 $(this) 的區別
編輯:JQuery特效代碼     
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的好處是它包裝了各種浏覽器版本對DOM對象的操作,因此統一使用$(this)而不再用this應該是比較不錯的選擇。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved