jquery $(this)和this

來源:互聯網
上載者:User

標籤:

jQuery中this與$(this)的區別

  1. $("#textbox").hover(   
  2.       function() {   
  3.            this.title = "Test";   
  4.       },   
  5.       fucntion() {   
  6.           this.title = "OK”;   
  7.       }   
  8. ); 

這裡的this其實是一個Html 元素(textbox),textbox有text屬性,所以這樣寫是完全沒有什麼問題的。
但是如果將this換成$(this)就不是那回事了,Error--報了。this與$(this)的區別在此。

  1. Error Code:   
  2. $("#textbox").hover(   
  3.        function() {   
  4.           $(this).title = "Test";   
  5.        },   
  6.        function() {   
  7.           $(this).title = "OK";   
  8.        }   
  9. ); 

這裡的$(this)是一個JQuery對象,而jQuery對象沒有title 屬性,因此這樣寫是錯誤的。

JQuery擁有attr()方法可以get/set DOM對象的屬性,所以正確的寫法應該是這樣:

正確的代碼:

  1. $("#textbox").hover(   
  2.       function() {   
  3.          $(this).attr(’title’, ‘Test’);   
  4.       },   
  5.       function() {   
  6.          $(this).attr(’title’, ‘OK’);   
  7.       }   
  8. ); 

使用jQuery的好處是它包裝了各種瀏覽器版本對DOM對象的操作,因此統一使用$(this)而不再用this應該是比較不錯的選擇。

jQuery中this與$(this)的區別就介紹到這裡。

jquery $(this)和this

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.