在不指定任何元素的情况下调用 jQuery 插件

2022-01-11 00:00:00 jquery jquery-plugins javascript

假设我有以下 jQuery 插件:

Say I have the following jQuery plugin:

$.fn.myPlugin = function () {
    //plugin code
}

通常,您在一定数量的元素上调用插件,例如:

Normally, you call a plugin on a certain number of elements, like such:

$("body").myPlugin();

<小时>

有什么方法可以在不指定元素的情况下调用我的插件?


Is there any way I can call my plugin without specifying an element?

我试过这样称呼它:$.myPlugin();,但这不起作用.

I have tried calling it like such: $.myPlugin();, but that does not work.

什么是这样:$().myPlugin();,但这是调用它的正确方法吗?

What works is this: $().myPlugin();, but is that the correct way to invoke it?

推荐答案

快速的写法是这样的:

$.myPlugin = function () {
    // Plugin code
}

正确的写法是这样的:

(function ($) {
    $.extend({
        myPlugin: function () {
            // plugin code
        }
    });
})(jQuery);

一开始可能有点混乱,但这是一个常见的 jQuery 模式.

It might seem a little confusing at first, but it's a common jQuery pattern.

(function($){
     // Code
})(jQuery);

这段代码创建了一个匿名函数并通过 jQuery 作为参数调用它.在函数内部,此参数绑定到 $.这样做的原因是它允许您使用 $ 即使 jQuery 在 无冲突模式.

This code creates an anonymous function and calls it passing jQuery as argument. Inside the function this argument is bound to $. The reason this is done it that it allows you to work with the $ even if jQuery is running in no-conflict mode.

第二部分是$.extend.当使用单个参数调用时,它基本上扩展了 jQuery 对象本身.

The second part is $.extend. It basically extends the jQuery object itself, when called with a single argument.

调用插件(在快速且正确的情况下)是:

Calling the plugin (in the quick and the right case) is:

$.myPlugin();

相关文章