如何将jquery插件选项true / false转换为更紧凑的形式?

时间:2012-02-23 10:23:24

标签: javascript jquery jquery-plugins options

在jquery插件选项中,您经常会看到如下所示的true和false:

var defaults = {
    one: 'false',
    two: 'true',
    three: 'true'
};

我想知道我是否可以做这样的事情:

var defaults = {
    doStuff: 'three two' // order of these wouldn't matter
};

上面的代码等于:

one == false
two == true 
three == true

问题是,我怎么能实现这个目标?

4 个答案:

答案 0 :(得分:2)

您可能需要like this

(function($){

    var defaults = {
        flags : ""
    }

    $.myPlugin = function(options){
        options = $.extend(true, {}, defaults, options);

        $.each(options.flags.split(" "), function(i, v){
            options[v] = true;
        });

        if (options.one) {
            alert("one setted");
        }

        if (!options.three) {
            alert("three not set");
        }

    }


})(jQuery);


$.myPlugin({flags: "one two"});

答案 1 :(得分:0)

您可以将收到的字符串拆分为数组,然后浏览每个项目并将每个项目视为“true”。

答案 2 :(得分:0)

第一种方法是首选方法,因为代码的作用更为明显。紧凑性通常不会优于可读性。

答案 3 :(得分:0)

您可以使用1和0而不是true和false,这样可以节省大量字符。