2009-08-07 38 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

您可以創建一個簡單的插件來做到這一點。

很多關於的文章。見this一個在jQuery的網站獲取更多信息

$(function(){ 

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

}); 

然後調用它

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

什麼'changeAnchorText()'? ;-) – Tomalak 2009-08-07 11:08:41

+0

@Tomalek:「doSomething」的例子。 – Thilo 2009-08-07 11:13:35

+0

它看起來是這樣...是的... – redsquare 2009-08-07 11:20:24

1

似乎你想要的東西,像jquery插件工作。

(function($){ 

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

     doSomething: function(options) { 

     return this.each(function() { 

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

     }); 
    } 
}); 

})(jQuery);