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.
Explanation:
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()
.
What I'd tried:
(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);
Simple call to create the elements:
$("#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?