Calling a jQuery plugin without specifying any elements(在不指定任何元素的情况下调用 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 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在不指定任何元素的情况下调用 jQuery 插件


基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01