2012-01-17 4 views
1

jquery를 처음 사용했습니다. this$(this)의 차이점을 알고 싶습니다. 난 방화를 사용할 때이

$.fn.column = function() { 

    var $td = this; 
    var $td1 = $(this); 


}; //end of $.fn.column = function() 

$('#FaqGridForm\\:faqGrid tr td').column(); 

같은 기능 콜을 가정하고 두 변수 [td]이다. 그럼이 둘의 차이점은 무엇입니까?

+0

가능한 중복 this와 $ (this) in jQuery?] (http://stackoverflow.com/questions/6965979/what-is-the-difference-between-this-and-this-in-jquery) – adatapost

+0

가능한 중복 [jQuery $ (this) vs this] (http://stackoverflow.com/questions/1051782/jquery-this-vs-this) –

+0

@Dupes, 올바른 복제본 찾기 : 플러그인의 컨텍스트에서'this' .. –

답변

3

jQuery 플러그인에서 this은 일치하는 모든 요소의 jQuery 컬렉션을 가리 킵니다. 이 문맥에서 $(this)을 사용하는 것은 더 이상 사용되지 않으며 을 권장하지 않습니다.

예를 들어, 이벤트 처리기의 컨텍스트에서 this은 이벤트가 발생한 DOM 요소를 가리 킵니다. $(this)은 jQuery 객체에 DOM 요소를 래핑하므로 jQuery 메서드를 사용할 수 있습니다.

코드 예제 :

$.fn.plugin = function() { alert(this); }; 
$('selector').plugin(); //Alerts [object Object] = a jQuery object. 

$('body').click(function() { 
    alert(this); // [object HTMLBodyElement] 
    alert($(this));// [object Object] (a jQuery object) 
}); 
+0

@James Allardice Rory McCrossan. 방금 다른 걸 찾았 어. 나는이 코드를 고소하고있다. $ ('# faqGrid tr td'). (function {) {var $ tdChildrenArray = $ (this) .children(); var $ divChildrenArray = this.children ('div');}); '내가 사용한다면'var $ tdChildrenArray = this.children(); var $ tdChildrenArray = this.children();'줄을 실행 한 후에 오류가 발생하지만 var $ tdChildrenArray = $ (this)를 사용하면 ' .children();'이면 오류가 없습니다. 왜? – Basit

+0

@Basit -이 경우'this'는 jQuery 객체가 아니라 DOM 요소를 참조하기 때문입니다. 내 대답을 보라. –

+0

jQuery 콜백에서'this'는 ** 일반적으로 ** DOM 요소를 가리킬 것이므로'this'는 jQuery 객체에 래핑되어야합니다. ** ** 당신의 질문에서와 같이,'this'는 항상'plugin'이 호출 된 selector와 일치하는 jQuery 객체를 가리 킵니다. –

0

this 문제의 기본 DOM 요소입니다. DOM 메서드의 전체 영역을 사용할 수 있습니다.

$(this)은 jQuery 객체로 래핑 된 네이티브 DOM 요소이므로 jQuery가 제공하는 모든 기능에 액세스 할 수 있으므로 필요에 따라 요소를 수정하는 프레임 워크가 제공됩니다. 또한 사용하여 jQuery 오브젝트를 통해 DOM 요소 자체에 액세스 할 수 있습니다 : 이것은 분명히 외부 기능에 jQuery를 쓰기에 적용

$("#myElement")[0] 

업데이트

. Rob W는 예제가 플러그인을 사용한다는 점에서 옳다. 따라서 this은 요소를 포함하는 jQuery 객체를 참조한다.

1

그런 경우 실제 차이점은 없습니다. jQuery를 확장 했으므로 this은 이미 jQuery의 인스턴스이고 모두 $(this)은 jQuery에 다시 전달하므로 필요하지 않습니다.

그러나,이 같은 경우에 : 당신이 그것에 jQuery를 방법을 사용할 수 있도록

$("#someElem").click(function() { 
    //this is now a reference to a DOM element: 
    console.log(this instanceof jQuery); //false 
    console.log(this.val()); //TypeError 
}); 

당신은 종종 jQuery를에 this 전달해야합니다

$("#someElem").click(function() { 
    console.log($(this) instanceof jQuery); //true 
    console.log($(this).val()); //Prints value 
}); 
의 차이 사이는 무엇입니까 [의
+0

두 번째 예제에서'this'는'$ (this)'이어야합니다. –

+0

죄송합니다. 감사. –

관련 문제