编写一个返回值的jQuery插件

Eri*_*lli 6 jquery jquery-plugins chaining jquery-chaining

我正在编写一个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);
Run Code Online (Sandbox Code Playgroud)

简单调用创建元素:

$("#someElement").myPlugin();
Run Code Online (Sandbox Code Playgroud)

在这里,我试图获得索引,没有成功:

alert($("#someElement").myPlugin("getSelection"));
Run Code Online (Sandbox Code Playgroud)

那么,有可能做我正在尝试的事情吗?

Nic*_*ver 12

您需要更改一下订单,如下所示:

(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);
Run Code Online (Sandbox Code Playgroud)

您可以像这样获得点击的索引:

alert($("#someElement").myPlugin("getSelection"));
Run Code Online (Sandbox Code Playgroud)

你可以在这里尝试一下,根本问题是你试图从.each()循环中返回一个值,这是行不通的.这样就可以从匹配选择器的第一个对象中获取数据(#someElement在示例中).还.data()存储其他东西,所以你需要给你的价值一个关键,就像我'index'在上面的版本中使用的那样.