2

如果我扩展 jquery fn(如 $.fn.extend)我写我的插件:

(function($){
    $.fn.extend({
        functionName : function(){
             //function returns
             return this.each(function(){
                  $(this).append("<div>text</div>");
             });
        }
    });
})(jQuery);

当我想扩展 jQuery 命名空间时,我会这样写:

(function($){
    $.extend({
        functionName : function(){
             //function returns

        }
    });
})(jQuery);

我不知道在这种情况下如何写“返回”

4

2 回答 2

2

你可以在第二种情况下返回任何你喜欢的东西。例如想想$.each()vs $.get()。但是,如果我是你,我会避免将其用作函数命名空间——它会导致污染。相反,您应该保留它以在 jquery 命名空间下添加您自己的命名空间,例如:

(function($){
    $.extend({
        myNamspace : {
          functionName: function(){
            // return whatever
          }
        }
    }});
})(jQuery);
于 2009-12-14T00:53:38.160 回答
2

更新

当您执行涉及多个选择器的多项操作时,您必须确定最有意义的操作。如果一个选择器是主要焦点,但也影响其他项目,则将其编写为插件,并返回主要结果集,如下所示:

$.fn.myAction = function(secondarySelector){
      return this.each(function(){
          $(this).css('display', 'block');
          $(secondarySelector).hide();
      });
};

// Use:
// $(primarySelector).myAction(secondarySelector);
$("#id").myAction(".address"); // Chain continues after action

如果选择器的重要性都相同,那么只需创建一个不返回任何内容或根据成功返回true/的函数。false

构造代码的另一种方法:

extend 方法用于其他 OOP 框架,正如您所展示的,它也可以与 jQuery 一起使用。然而,您会发现,许多 jQuery 开发人员选择更短更明显的语法,如下所示:

(function($){

    // The if statement allows the file to be used with
    // other files that use the same shared namespace
    if(!$.Namespace){
        $.Namespace = { };
    };

    $.Namespace.Constructor = function( params ){
       ... code ...
    };

    // And for the wrapper sets ($.fn):
    $.fn.functionName = function(opts){
       return this.each(function(){
          ... code ...
       });
    };

})(jQuery);
于 2009-12-14T01:11:02.490 回答