jQuery $.function()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1618205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:50:54  来源:igfitidea点击:

jquery $.function()

jqueryfunction

提问by kmunky

How can I write a plugin/function and then be able to call it like this(no selector required)?

我如何编写插件/函数然后能够像这样调用它(不需要选择器)?

$.function()

now I'm writing my plugins something like this:

现在我正在编写这样的插件:

(function($){
     $.fn.extend({
          //function name
          myFunction : function(){
           //...........
          }
     });
})(jQuery);

回答by emills

While the "extend" jquery function is the correct way to extend the library, it has two forms.

虽然“扩展”jquery 函数是扩展库的正确方法,但它有两种形式。

$.fn.extend which is what you are using in your example is used to add additional functions to actual DOM objects. So for example your "myFunction" function could be used like this if you wanted to take an action on the "document" object in the dom. $(document).myFunction()

$.fn.extend 这是您在示例中使用的内容,用于向实际 DOM 对象添加附加功能。因此,例如,如果您想对 dom 中的“文档”对象执行操作,则可以像这样使用“myFunction”函数。$(document).myFunction()

To extend the static namespace of jQuery, you need to use the $.extend function instead (note the lack of fn)

要扩展jQuery的静态命名空间,需要改用$.extend函数(注意缺少fn)

(function($){
 $.extend({
      //function name
      myFunction : function(){
       //...........
      }
 });
})(jQuery);

should be what you are looking for.

应该是你正在寻找的。

回答by Greg

Simply like this:

就像这样:

(function($){
     $.myFunction = function(){
           //...........
          }
})(jQuery);

Or just:

要不就:

jQuery.myFunction = function() { ... };