如何在jQuery中使用$(this)来改进这段代码?

时间:2009-08-07 10:42:12

标签: javascript jquery

我有以下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

2 个答案:

答案 0 :(得分:3)

您可以创建一个简单的插件来执行此操作。

很多关于的文章。有关详细信息,请参阅jQuery网站上的this一个

$(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");

答案 1 :(得分:1)

似乎你想要一些像jquery插件一样的东西。

(function($){

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

      doSomething: function(options) {

        return this.each(function() {

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

        });
    }
});

})(jQuery);