jQuery插件如何加载元素集合?

Zer*_*ide 6 jquery jquery-plugins

我不确定这是否是一个stackoverflow问题,因为它是一般的所以原谅我,如果是的话.

假设我有以下标记:

<div class="plugin"> ... </div>
<div class="plugin"> ... </div>
<div class="plugin"> ... </div>
Run Code Online (Sandbox Code Playgroud)

我不想运行一个jquery插件并将它传递给每个具有plugin该类的元素:

$(".plugin").myPlugin();
Run Code Online (Sandbox Code Playgroud)

插件代码看起来像这样:

;(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));
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,看起来像是为每个具有类名称的元素调用插件构造函数myPlugin.我认为它将在整个div集合上运行插件,并且只调用一次构造函数.

那么它是怎样工作的?是为类选择器返回的每个元素创建的插件实例吗?

Dav*_*ing 1

\n

是否为类选择器返回的每个元素创建了一个插件实例?

\n
\n\n

是的。因为当您this.each在插件构造函数内部调用并Plugin为每个元素初始化一个新的构造函数时,您正在循环遍历元素。

\n\n

如果您想为集合运行单个自定义构造函数,请 don\xe2\x80\x99t do this.each,只需传递thisPlugin构造函数(尽管您可能必须使用 重新考虑插件的“缓存” jQuery.data

\n