jQuery插件$ .extend [英] jquery plugin $.extend

查看:90
本文介绍了jQuery插件$ .extend的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我扩展了jQuery fn(例如$ .fn.extend),我会写我的插件:

if i extend the jquery fn(like $.fn.extend) i write my plugin:

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

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

when i want to extend jQuery namespace i write it like this:

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

        }
    });
})(jQuery);

在这种情况下,我不知道如何写"return"

what i don't know is how to write the 'return' in this case

推荐答案

更新

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

When you are doing multiple operations involving more than one selector, you have to decide what makes the most sense. If one selector is the primary focus, but effects other items as well, write it like a plugin, and return the primary result set like this:

$.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的函数.

If the selectors are all equal in importance, then simply create a function that does not return anything or returns true / false depending on success.

另一种构建代码的方式:

extend方法在其他OOP框架中使用,并且如您所显示,也可以与jQuery一起使用.但是,您会发现许多jQuery开发人员都选择了更短的,更明显的语法,如下所示:

The extend method is used in other OOP frameworks and as you have shown, can be used with jQuery as well. What you will find, however, is many jQuery developers opt for the shorter more obvious syntax like this:

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

这篇关于jQuery插件$ .extend的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆