3

我想在 jquery 插件实例(我创建的一个)之间共享属性和方法我将如何正确地做到这一点?

假设我有一个简单的插件定义为:

// add the plugin to the jQuery.fn object
$.fn.clickableImage = function(options) {

    this.set_not_clicked = function(){
      return this.each(function() {
        $(this).addClass('not-clicked');
      });

    };

    // iterate through the DOM elements we are attaching the plugin to
    return this.each(function() {
      $(this).click( function(){
        parent.set_not_clicked() //how to get "parent" ???
        $(this).removeClass('not-clicked').addClass('clicked');
      });
    });
}

并且,图像实例化为:

$(function(){
  $('#some-selector img').clickableImage();
});

如何让“clickableImage”知道其他“clickableImage”?

4

1 回答 1

2

闭包是 javascript 中的一种常见模式,因为它们可以防止全局名称空间污染。

有关详细信息,请参阅此 SO 问题:JavaScript 中的“闭包”到底指的是什么?

“闭包”是一个表达式(通常是一个函数),它可以具有自由变量以及绑定这些变量(“关闭”表达式)的环境。

在你的情况下,这看起来像这样:

(function($){
   var instances = [];
   function count(){
     alert(instances.length);
   }

   function hide_parent(){
     for(var i=0;i<instances.length;i++){
       $(instances[i]).parent().hide();
     }
   }

   $.fn.clickableImage = function(options) {

    // Use a class to prevent double bindings.       
    this
     .filter(':not(.clickImage)')
     .addClass('clickImage')
      // iterate through the DOM elements we are attaching the plugin to
     .each(function() {
        instances.push(this);
        $(this).click( function(){
          // Alert the current image count:
          count(); 
          // Hide all parents:
          hide_parent();
        })
      })

    return this;
  }
}(jQuery));

alert(typeof instances);// will return undefined

您还可以添加一个类并在 dom 中搜索您的类:

$.fn.clickableImage = function(options) {
    // iterate through the DOM elements we are attaching the plugin to
    return this
      .addClass('clickImage')
      .each(function() {
      $(this).click( function(){
        $("img.clickImage").each(function(){
          $(this).parent().hide();
        });
        alert(instances_count);
      });
    });
}
于 2012-08-11T20:46:32.170 回答