如何在jquery插件中包含可选参数

时间:2014-01-22 22:09:06

标签: jquery

(function ( $ ) {
    $.fn.greenify = function( options ) {
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options );
        // Greenify the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });
    };
}( jQuery ));

Docs获取上面的代码显示了如何创建一个简单的jquery插件。如果我只提供接受多个插件中列出的多个参数之一,该怎么办?适用哪些?

如果我有一个可以接受多个参数的插件,那么这些参数将应用于以下内容:

$.doStuff({color:"black"},{color:"blue"});

当只提供一组参数时,哪些选项将被“扩展”?

E.x. $.doStuff({color:"black"});

1 个答案:

答案 0 :(得分:1)

如果调用参数多于参数变量的函数,并且函数不使用特殊arguments变量来访问变长参数,则会忽略额外参数。

所以在你的例子中:

$.greenify({color: "black"}, {color: "blue"});

options变量将设置为{color: "black"}{color: "blue"}参数将被忽略。

相关问题