2015-06-19 73 views
1

我一直在編寫jQuery插件工作數小時,閱讀文檔,搜索帖子等。有一件事尚不清楚。 我正在寫有多個實例的一個插件,所以我有這樣的事情編寫一個jQuery插件:公共方法和多個插件實例

<div id="box1" class="box"></div> 
<div id="box2" class="box"></div> 

<script type="text/javascript"> 
    $(".box").myPlugin(); 
</script> 

所以該插件將作用於兩個DOM元素。 這是一個插件演示。假設我需要一個或多個私有變量(演示中的myValue),當然任何實例(box1,box2)都有不同的值。

(function ($) { 

    $.fn.myPlugin = function() { 

     this.each(function() { 

      /* this is a private variable */ 
      var myValue = Math.floor(Math.random() * 10000); 
     }); 

     return this; 
    }; 

    /* this is a public method */ 
    $.fn.myPlugin.showValue = function() { 
     alert('My value is ' + myValue); 
    }; 

}(jQuery)); 

現在我需要這個插件來公開一個讀取/寫入這種私有變量的公共方法。上面的代碼當然會失敗,「myValue is undefined」錯誤。

我需要以某種方式獲得對任何實例的引用,然後調用「他們的」公共方法。類似於

$('#box2')。showValue()/ * ??? */

任何幫助將不勝感激。謝謝。

+0

看看:http://learn.jquery.com/plugins/basic-plugin-creation/ –

回答

1

不幸的是,沒有簡單的方法讓您的示例工作,而無需簡單定義$.fn namespace上的其他「插件」。

通常,一個插件的方法被實現爲參數傳遞給插件:

$("foo").myPlugin(); // initialize 
$("foo").myPlugin("doSomething"); // do something 

或通過具有可用的一個「實例」對象:

$("foo").myPlugin(); // initialize 
var inst = $("foo").data("myPlugin"); // get instance 
inst.doSomething(); // do something 

第一個選項的一個例子可以在這裏找到:http://learn.jquery.com/plugins/basic-plugin-creation/

+0

所以我的例子是 (函數($){ $ .fn.myPlugin =功能(作用){ \t this.each(功能(作用){ \t \t/*這是一個專用變量*/ \t \t變種myValue = Math.floor(Math.random()* 10000); \t \t \t 如果\t(動作=== '節目'){ \t \t \t警報( '我的值是' + myvalue的); \t \t} }); \t \t return this; }; }(jQuery)); 但這是正確的嗎?插入代碼是不是被稱爲4次(每個盒子兩次),而不是2? – user2029958

+0

這是正確的,您需要爲插件編寫該事實。 –