我正在编写一个 jQuery 插件,在某些情况下可以存储一些数据。
我想以一种非常灵活的方式编写它,我可以更改输入参数来获取插件存储的一些值。
解释:
当我打电话时$("#any").myPlugin()
,我的插件初始化创建一个div
还有一些a
里面。
单击一个a
将存储它.index()
使用.data()
方法。
如果我打电话$("#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"));
那么,可以做我正在尝试的事情吗?
您需要稍微改变一下顺序,如下所示:
(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"));
你可以在这里尝试一下 http://jsfiddle.net/nick_craver/75ppA/2/,根本问题是你试图从一个值中返回一个值.each() http://api.jquery.com/each/循环,这不起作用。相反,这会从与选择器匹配的第一个对象中获取数据(#someElement
在示例中)。还.data() http://api.jquery.com/data/ stores other事情,所以你需要给你的价值一个关键,就像我正在使用的'index'
在上面的版本中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)