代码之家  ›  专栏  ›  技术社区  ›  Mathias Bynens

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

  •  2
  • Mathias Bynens  · 技术社区  · 16 年前

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

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

    别担心 .text() 部分,事实上,我做的事情比这更复杂…但既然这和我的问题无关,我只是用 文本() 这里举个简单的例子。

    问题是,每次我打电话给 doSomething() 函数,代码如下:

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

    如你所见,我总是路过 $(this) 作为第一个论点。不知怎么的,我觉得这不是去的路…此函数是否可以改进,以便它自动继承 美元(这个) 从它被称为的上下文?可能有如下情况:

    $(this).doSomething(foo); // the foo argument is irrelevant
    $(this).doSomething(bar); // the bar argument is irrelevant
    
    2 回复  |  直到 11 年前
        1
  •  3
  •   redsquare    16 年前

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

    关于的文章很多。见 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");
    
        2
  •  1
  •   Anwar Chandra    16 年前

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

    (function($){
    
    //Attach doSomething method to jQuery
    $.fn.extend({ 
    
          doSomething: function(options) {
    
            return this.each(function() {
    
              var el = $(this);
              // do something here
    
            });
        }
    });
    
    })(jQuery);