jQuery裡$(this)和this的區別在哪?

來源:互聯網
上載者:User

如果你要使用html元素本身的屬性或方法就需要使用this,如果你要使用jQuery封裝後的方法或屬性就要$(this),一般則有如下的關係.

$(this)[0] == this;上文的代碼是要使用this的地方是要調用表單form的有reset方法,而這一方法jQuery沒有封裝支援,所以才有this.reset(),也可以使用$(this)[0].reset();

關於什麼時候使用二者?可以看如下例子:


[html] 
<a href="http://segmentfault.com/q/1010000000125418" target="_blank" data-id="1010000000125418">jQuery</a> 

<a href="http://segmentfault.com/q/1010000000125418" target="_blank" data-id="1010000000125418">jQuery</a>
[javascript] view plaincopyprint?
$('a').click(function(){ 
        this.innerHTM==$(this).html()=='jQuery';//三者是一樣的.  
        this.getAttribute('href')==this.href==$(this).attr('href')//三者是一樣的;  
        this.getAttribute('target')==this.target==$(this).attr('target')//三者是一樣的;  
        this.getAttribute('data-id')==$(this).attr('data-id')//二者是一樣的;  
    }); 

$('a').click(function(){
        this.innerHTM==$(this).html()=='jQuery';//三者是一樣的.
        this.getAttribute('href')==this.href==$(this).attr('href')//三者是一樣的;
        this.getAttribute('target')==this.target==$(this).attr('target')//三者是一樣的;
        this.getAttribute('data-id')==$(this).attr('data-id')//二者是一樣的;
    });
從以上代碼可以看出二者的差異.

 

 

或者 簡單理解:

this是html元素對象吧~
$(this)成為jQuery對象


或者 :


this 是 JavaScript 中的關鍵字。
$(this) 可以認為是用 jQuery 封裝過 JavaScript 中的 this,封裝後 $(this) 就會繼承 jQuery 的方法。

 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.