問題描述
假設我有以下 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 插件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!