插件方法——这里的神奇之处是什么?

plugin methods - what's the magic here?

本文关键字:是什么 方法 这里 插件 神奇      更新时间:2023-09-26

我努力了一下,终于让[这个]工作了。现在,我想把它分解如下图所示,但它不起作用…这里有什么我不明白的巫毒吗?

<!DOCTYPE html>
<html>
<head>
<!-- jQuery -->
<script type="text/javascript" src="http://goo.gl/XQPhA"></script>
<script type="text/javascript">
(function($) {
    $.test = function(options) {
        options = $.extend({}, $.test.settings, options);
        this.whiten = function() {
            $(this).css('background-color', options.bg);
        };
    };
    $.test.settings = { bg: 'white' };
    $.fn.test = function(options) {
        return this.each(function(index, el) {
            $.test(options);
        });
    };
})(jQuery);
$(document).ready(function() {
    $('ul').test().css('background-color', 'wheat');
    $('#go').click(function() {
        $('ul').whiten();
    });
});
</script>
</head>
<body>
<button id="go">whiten</button>
<ul id="list1">
<li>Aloe</li>
<li>Bergamot</li>
<li>Calendula</li>
<li>Damiana</li>
<li>Elderflower</li>
<li>Feverfew</li>
</ul>
<ul id="list2">
<li>Ginger</li>
<li>Hops</li>
<li>Iris</li>
<li>Juniper</li>
<li>Kavakava</li>
<li>Lavender</li>
<li>Marjoram</li>
<li>Nutmeg</li>
<li>Oregano</li>
<li>Pennroyal</li>
</ul>
</body>
</html>

与前面的代码相比,在each()循环中,我现在称为$.test(options)而不是$.fn.test(options) -那么为什么一个工作而不是另一个(实际上,为什么/如何开始第一个工作)?

我将重构您的插件,以遵循插件创作指南中概述的指导方针,最值得注意的是使用.data()存储小部件设置的数据,并使用.test("method")对插件进行方法调用:

(function($) {
    /* Default plugin settings: */
    var settings = {
        bg: 'white'
    };
    /* Method definitions: */
    var methods = {
        init: function(options) {
            options = $.extend({}, options, settings);
            return this.each(function () {
                $(this).data("test", options);
            });
        },
        whiten: function() {
            var options = this.data("test");
            this.css('background-color', options.bg);
        }
    };
    /* Plugin definition and method calling logic: */
    $.fn.test = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist');
        }
    }
})(jQuery);

用法:$("elem").test(), $("elem").test("whiten")

下面是一个工作示例:http://jsfiddle.net/z4R3X/

jQueryUI源代码是插件创作指导的另一个资源(以自动完成小部件为例)。这些小部件是如何创建可重用的、可读的jQuery插件的很好的例子。