编写一个返回值的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('<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"));

You can give it a try here,根本问题是你试图从.each()循环中返回单个值,这不起作用.这样就可以从匹配选择器的第一个对象(示例中的#someElement)中获取数据.另外.data()存储其他东西,所以你需要给你的价值一个关键,就像我在上面的版本中使用’index’.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...