2011-06-26 19 views
-1

可能重複的區別:
What's the difference between $(this) and this in jQuery?

jquery selector,示例代碼:

<body> 
    <select name="garden" multiple="multiple"> 

    <option>Flowers</option> 
    <option selected="selected">Shrubs</option> 
    <option>Trees</option> 
    <option selected="selected">Bushes</option> 

    <option>Grass</option> 
    <option>Dirt</option> 
    </select> 
    <div></div> 
<script> 

    $("select").change(function() { 
      var str = ""; 
      $("select option:selected").each(function() { 
       str += $(this).text() + " "; // I interested it this line 
       }); 
      $("div").text(str); 
     }) 
     .trigger('change'); 
</script> 

</body> 

在這個例子中代碼,有一部分代碼:

str += $(this).text() + " "; 

我想知道,爲什麼這裏不使用str += this.text() + " ";?換句話說,爲什麼不使用this,而是在那部分代碼中使用$(this)?在這種情況下this$(this)有什麼區別?

+1

重複[$(this)和jQuery中的這個有什麼區別?](http://stackoverflow.com/questions/3685508/whats-the-difference-between-this-and-this-in-jquery )和/或[jQuery $(this)vs this](http://stackoverflow.com/questions/1051782/jquery-this-vs-this)和/或其他幾個:-) –

回答

3

jQuery的each功能設置this爲每個調用迭代回調(docs)的原料 DOM元素。在該原始元素上調用$()會爲您提供一個包裹它的jQuery對象,讓您可以訪問jQuery的功能,如text

1

this是一個標準的javascript obect,$(this)是jQuery包裝的對象,暴露了像常規JavaScript沒有的函數和屬性一樣的所有jQuery優點。

有時不需要jQuery包裝,可能會被視爲矯枉過正。

0

出於同樣的原因,您使用$("select")而不是select。它將對象放入正確的jQuery上下文中並返回jQuery包裝的對象。

0

$(「this」)是jquery,'this'是javascript。