在不指定任何元素的情况下调用 jQuery 插件 [英] Calling a jQuery plugin without specifying any elements

查看:13
本文介绍了在不指定任何元素的情况下调用 jQuery 插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 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();

这篇关于在不指定任何元素的情况下调用 jQuery 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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