Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在jQuery中使用$(this)改进此代码?_Javascript_Jquery - Fatal编程技术网

Javascript 如何在jQuery中使用$(this)改进此代码?

Javascript 如何在jQuery中使用$(this)改进此代码?,javascript,jquery,Javascript,Jquery,我有以下jQuery函数(简化): 不要担心.text()部分,实际上我正在做的事情比这更复杂一些。。。但由于这与我的问题无关,所以我在这里仅使用.text()作为一个简单的示例 问题是,每次我调用doSomething()函数时,代码如下所示: doSomething($(this), foo); // the second argument is irrelevant doSomething($(this), bar); // the second argument is irrelevan

我有以下jQuery函数(简化):

不要担心
.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

似乎您需要类似jquery插件的东西

(function($){

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

      doSomething: function(options) {

        return this.each(function() {

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

        });
    }
});

})(jQuery);

您可以创建一个简单的插件来实现这一点

很多关于这个的文章。有关更多信息,请参见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");
什么是
changeancortext()
?;-)@托马莱克:“doSomething”的一个例子。
$('div').changeAnchorText("Any descendant anchor tags inside this div with a class of someClass will have the text changed to this message");