微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

编写一个返回值的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’.

原文地址:https://www.jb51.cc/jquery/176886.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐