2009-08-07 2 views
2

나는 다음과 같은 jQuery를 기능 (간체)이 있습니다

function doSomething(el, str) { 
el.find('.class').text(str)); 
} 

에서, .text() 부분에 대해 걱정하지 마십시오 현실에서 나는 것보다 좀 더 복잡한 무언가를 ...하고 있어요하지만 이후 그 무관의 내 질문, 난 그냥 .text() 여기 간단한 예제로 사용하고 있습니다.

이 문제는, 매번 나는 doSomething() 함수를 호출하고있어, 코드는 다음과 같습니다 : 당신이 볼 수 있듯이

doSomething($(this), foo); // the second argument is irrelevant 
doSomething($(this), bar); // the second argument is irrelevant 

, 나는 항상 첫 번째 인수로 $(this)를 전달하고있다. 어떻게 든이 방법은 갈 길이 없다고 느낍니다.이 기능을 개선하여 호출 된 컨텍스트에서 $(this)을 자동으로 상속 할 수 있습니까? 다음과 같을 수도 있습니다.

$(this).doSomething(foo); // the foo argument is irrelevant 
$(this).doSomething(bar); // the bar argument is irrelevant 

답변

3

간단한 플러그인을 만들어이 작업을 수행 할 수 있습니다.

에 대한 기사가 많이 있습니다. 더 많은 정보를 위해 jQuery를 사이트에 this 하나를 참조하십시오

$(function(){ 

    jQuery.fn.changeAnchorText = function(str) { 
    return this.each(function(){ 
     $(this).find('a.someClass').text(str); 
    }); 
    }; 

}); 

는`changeAnchorText()`이 무엇

$('div').changeAnchorText("Any descendant anchor tags inside this div with a class of someClass will have the text changed to this message"); 
+0

호출 할? ;-) – Tomalak

+0

@Tomalek : "doSomething"의 예. – Thilo

+0

그런 식으로 보입니다 ... – redsquare

1

jquery 플러그인처럼 작동하는 것으로 보이십니까?

(function($){ 

//Attach doSomething method to jQuery 
$.fn.extend({ 

     doSomething: function(options) { 

     return this.each(function() { 

      var el = $(this); 
      // do something here 

     }); 
    } 
}); 

})(jQuery); 
관련 문제