编写一个返回值的jQuery插件
我正在编写一个jQuery插件,在某些情况下存储一些数据。
我想以一种非常灵活的方式编写它,我可以更改输入参数以获取插件存储的某些值。
说明:
当我调用$("#any").myPlugin()
,我的插件初始化创建一个div
而一些内部。 单击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(''); var div = $("div", $this); div.append('A').append('B').append('C'); 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"));
那么,有可能做我正在尝试的事情吗?
您需要更改一下订单,如下所示:
(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(''); var div = $("div", $this); div.append('A').append('B').append('C'); 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"));
你可以在这里尝试一下 ,根本问题是你试图从.each()
循环中返回单个值,这不起作用。 这样就可以从匹配选择器的第一个对象( #someElement
中的#someElement
)中获取数据。 另外.data()
存储其他东西,所以你需要给你的值一个键,比如我在上面的版本中使用'index'
。
我相信这条线是你的问题开始的地方
if (action == null) action = "initialize";
好像你在没有指定参数的情况下调用插件一样,动作将是未定义的(非空)。
你可以考虑改变它
if (!(action)) action = "initialize";
编辑:进一步观察,我认为问题是,当您设置数据时,根据.data()方法的文档,您永远不会给它一个键
存储数据使用:
$this.data("selectedValue",$(this).index());
并检索它像这样:
$('#plugin-container').data("selectedValue")
看到工作小提琴 – > http://jsfiddle.net/7MAUv/