2013-06-19 54 views
-1
<!doctype html> 
<html> 
    <head> 
     <meta charset="utf-8" /> 
     <title>Demo</title> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
     <script> 
      var headings = $('h3'); 
      var paras = $('p'); 
      paras.hide().eq(0).show(); 
      headings.click(function() { 
       var cur = $(this); //save the element that has been clicked for easy referal 
       cur.siblings('p').hide(); //hide all the paragraphs 
       cur.next('p').show(); //get the next paragraph after the clicked header and show it 
      }); 
     </script> 
     <style type="text/css"> 
      p,h3 {margin: 0; padding: 0;} 
      p {height: 150px; width: 200px; border: 1px solid black;} 
      h3 {height: 50px; width: 200px; background-color: blue; color: white; border: 1px solid black;} 
     </style> 
    </head> 
    <body> 
     <h3>Item 1 </h3> 
     <p>Item 1 content</p> 
     <h3>Item 2 </h3> 
     <p>Item 2 content</p> 
     <h3>Item 3 </h3> 
     <p>Item 3 content</p> 
     <h3>Item 4</h3> 
     <p>Item 4 content</p> 
    </body>  
</html> 

上面的代碼是從這裏取:http://www.1stwebdesigner.com/tutorials/jquery-for-complete-beginners-part-3/

問:

這條線:var cur = $(this);我知道this是指已被點擊h3,但爲什麼我們不能這樣寫:var cur = this;this$(this)這裏有什麼區別?

回答

4
$(this) 

將通過this返回到jQuery對象的DOM元素,置身其中,你就可以繼續使用jQuery。

1

this是調用當前函數

例如

$(document).ready(function(){ 
    $("#test").click(function(){ 

var jQuerizedElement = $(this); // instead of calling it by its selector you can use this 
    }); 
}); 

現在你可以做更多的東西與它的成員的引用。

1

this返回DOM元素,而$(this)返回jQuery對象。

this 

相當於

$(this).get() 
0

$爲jQuery函數的簡寫。你也可以這樣寫:

var cur = jQuery(this); 

jQuery「包裝」DOM元素和其他對象,以便爲它們提供更多功能。就像您將選擇器字符串傳遞給jQuery構造函數一樣,您可以傳遞本地DOM元素(即this),它將成爲jQuery對象。