2010-09-02 24 views
5

我正在寫一個存儲某些數據的jQuery插件。編寫一個返回值的jQuery插件

我想以非常靈活的方式編寫它,我可以在其中更改輸入參數以獲取由插件存儲的某些值。

說明:

當我打電話$("#any").myPlugin(),我的插件將初始化創建div和一些a內。 點擊一個a將使用.data()方法存儲它.index()。 如果我打電話給$("#any").myPlugin("getSelection"),那麼我想用.data()得到存儲的值。

我已經試了一下:

(function ($) { 
    $.fn.myPlugin = function (action) { 
     if (action == null) action = "initialize"; 

     return this.each(function ($this) { 
      $this = $(this); 

      if (action == "initialize") { 
       $this.html('<div></div>'); 
       var div = $("div", $this); 

       div.append('<a>A</a>').append('<a>B</a>').append('<a>C</a>'); 

       div.children("a").each(function (i) { 
        $(this).click(function (event) { 
         // Here I store the index. 
         $this.data($(this).index()); 
         event.preventDefault(); 
         return false; 
        }); 
       }); 

       return $this; 
      } else if (action == "getSelection") { 
       // With this action, I tried to get the stored value. 
       return $this.data("selectedValue"); 
      } 
     }); 
    }; 
})(jQuery); 

簡單的調用創建的元素:

$("#someElement").myPlugin(); 

在這裏,我會試圖讓索引,而不sucess:

alert($("#someElement").myPlugin("getSelection")); 

那麼,有可能做我想要的嗎?

回答

11

您需要更改起來整理了一下,像這樣:

(function ($) { 
    $.fn.myPlugin = function (action) { 
     action = action || "initialize"; 

     if (action == "getSelection") { 
      return this.data('index'); 
     } 

     return this.each(function ($this) { 
      $this = $(this); 

      if (action == "initialize") { 
       $this.html('<div></div>'); 
       var div = $("div", $this); 

       div.append('<a>A</a>').append('<a>B</a>').append('<a>C</a>'); 

       div.children("a").each(function (i) { 
        $(this).click(function (event) { 
         // Here I store the index. 
         $this.data('index', $(this).index()); 
         event.preventDefault(); 
         return false; 
        }); 
       }); 

       return $this; 
      } 
     }); 
    }; 
})(jQuery); 

的,你可以得到的點擊指數走出這樣的:

alert($("#someElement").myPlugin("getSelection")); 

You can give it a try here,根本問題是你試圖從.each()循環中返回一個值,這是行不通的。這取代了匹配選擇器的第一個對象的數據(示例中的#someElement)。另外.data()其他東西,所以你需要給你的價值一個關鍵,就像我在上面的版本中使用'index'

1

我相信這條線是你的問題開始

if (action == null) action = "initialize"; 

,如果你調用插件,而無需指定參數,操作將是不確定的(不爲空)。

,你可以考慮改變這

if (!(action)) action = "initialize"; 

編輯:具有進一步看,我認爲這個問題是,當你設置的數據,你永遠不會根據Documentation of .data() method

商店給它一個關鍵的使用數據:

$this.data("selectedValue",$(this).index()); 

並檢索它像這樣:

$('#plugin-container').data("selectedValue") 

看到這裏的工作小提琴 - >http://jsfiddle.net/7MAUv/

+0

感謝指出未定義,但它可能會影響只是初始化。沒有解決設置正確操作時的返回問題。 – 2010-09-02 14:51:33

+0

但是,初始化不起作用,你永遠不會獲得新的元素,不會附加點擊事件,也不會設置數據。因此,在使用getSelection參數調用時,您將永遠不會獲得選擇。 – Jamiec 2010-09-02 15:02:31