JQuery this 和 $(this) 的區別


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM