2013-06-19 4 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> 

여기에서 가져옵니다 왜 우리는 이런 식으로 쓸 수 없습니까? var cur = this;this$(this)의 차이점은 무엇입니까?코드 위

답변

4
$(this) 

당신이에 jQuery를 계속 사용할 수있는로부터의 jQuery 객체에 this에 의해 반환 된 DOM 요소를 변환합니다.

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 객체가됩니다.

관련 문제