2009-08-07 84 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);