我不确定这是否是一个stackoverflow问题,因为它有点笼统,如果是,请原谅我。
假设我有以下标记:
<div class="plugin"> ... </div>
<div class="plugin"> ... </div>
<div class="plugin"> ... </div>
而且我不想运行一个 jquery 插件并将每个具有plugin
该类的元素传递给它:
$(".plugin").myPlugin();
插件代码如下所示:
;(function ( $, window, undefined ) {
var myPlugin = 'myPlugin',
document = window.document,
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = myPlugin;
this.init();
}
Plugin.prototype.init = function () {
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[myPlugin] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + myPlugin)) {
$.data(this, 'plugin_' + myPlugin, new Plugin( this, options ));
}
});
}
}(jQuery, window));
当我运行这段代码时,看起来插件构造函数正在为每个类名为myPlugin
. 我认为它会在整个 div 集合上运行插件,并且只调用一次构造函数。
那么它是怎样工作的?是否为类选择器返回的每个元素创建了插件实例?