且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

编写一个返回值的jQuery插件

更新时间:2023-11-20 22:39:34

您需要稍微更改一下顺序,如下所示:

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.