【发布时间】:2011-04-07 09:20:19
【问题描述】:
我正在编写一个 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();
在这里我试图获取索引,但没有成功:
alert($("#someElement").myPlugin("getSelection"));
那么,有可能做我正在尝试的事情吗?
【问题讨论】:
标签: jquery jquery-plugins chaining jquery-chaining