编写一个返回值的jQuery插件 [英] Write a jQuery Plugin that return values
问题描述
我正在编写一个在某些情况下存储一些数据的jQuery插件.
I'm writing a jQuery plugin that stores some data in some cases.
我想以一种非常灵活的方式编写它,在这里我可以更改输入参数以获得一些由插件存储的值.
I'd like to write it in a very flexible way, where I'll can change an input parameter to obtain some value that were stored by the plugin.
说明:
当我调用$("#any").myPlugin()
时,我的插件将初始化创建一个div
和一些a
.
单击a
将使用.data()
方法将其存储为.index()
.
如果我调用$("#any").myPlugin("getSelection")
,那么我想获取存储在.data()
中的值.
When I call $("#any").myPlugin()
, my plugin initializes creating a div
and some a
inside.
Clicking on an a
will store it .index()
using the .data()
method.
If I call $("#any").myPlugin("getSelection")
then I would like to get the value stored with .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();
在这里,我试图获取索引,但没有成功:
And here I'd tried to get the index, without sucess:
alert($("#someElement").myPlugin("getSelection"));
那么,可以做我想做的事吗?
So, is possible to do what I'm trying?
推荐答案
您需要稍微更改一下顺序,如下所示:
You need to change up the order a bit, like this:
(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);
您可以像这样获得点击的索引:
The you can get the clicked index out like this:
alert($("#someElement").myPlugin("getSelection"));
您可以在此处尝试,基本问题是您正在尝试从 .each()
循环中返回单个值,该方法无效.而是从与选择器匹配的第一个对象(示例中为#someElement
)中获取数据.此外, .data()
存储其他内容,因此您需要提供自己的价值一把钥匙,就像我在上述版本中使用'index'
一样.
You can give it a try here, the fundamental problem is you're trying to return a single value out of a .each()
loop, which doesn't work. This instead grabs the data off the first object that matches the selector (#someElement
in the example). Also .data()
stores other things, so you need to give your value a key, like I'm using 'index'
in the version above.
这篇关于编写一个返回值的jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!