我正在寫一個存儲某些數據的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"));
那麼,有可能做我想要的嗎?
感謝指出未定義,但它可能會影響只是初始化。沒有解決設置正確操作時的返回問題。 – 2010-09-02 14:51:33
但是,初始化不起作用,你永遠不會獲得新的元素,不會附加點擊事件,也不會設置數據。因此,在使用getSelection參數調用時,您將永遠不會獲得選擇。 – Jamiec 2010-09-02 15:02:31