调用jQuery插件而不指定任何元素 [英] Calling a jQuery plugin without specifying any elements
问题描述
假设我有以下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屋!