JQuery this 和 $(this) 的區(qū)別
更新時間:2009年08月23日 19:00:13 作者:
起初以為this和$(this)就是一模子刻出來。但是我在閱讀時,和coding時發(fā)現,總不是一回事。
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對象的操作,因此統(tǒng)一使用$(this)而不再用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對象的操作,因此統(tǒng)一使用$(this)而不再用this應該是比較不錯的選擇。
相關文章
基于jQuery實現的Ajax 驗證用戶名是否存在的實現代碼
基于jQuery實現的Ajax 驗證用戶名是否存在的實現代碼,需要的朋友可以參考下。2011-04-04
jQuery使用serialize()表單序列化時出現中文亂碼問題的解決辦法
列化中文時出現中文亂碼問題,怎么回事呢?下面給大家介紹下jQuery使用serialize()序列化表單時出現中文亂碼問題的解決辦法,有需要的朋友參考下2016-07-07
jQuery插件jcrop+Fileapi完美實現圖片上傳+裁剪+預覽的代碼分享
這篇文章主要介紹了jQuery插件jcrop+Fileapi完美實現圖片上傳+裁剪+預覽的代碼,非常的簡單實用,效果也很棒,有需要的小伙伴可以參考下。2015-04-04
jQuery 驗證插件 Web前端設計模式(asp.net)
asp.net下用戶注冊頁面的驗證代碼,花了點時間將驗證做成一個jQuery插件,希望對需要的朋友有所幫助。2010-10-10

