如果你要使用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 的方法。