0

所以我正在尝试编写一个 jQuery 插件,我想设置三个值任何第一个设置的默认值。

这是我想要的更长的版本

config.duration = 350;
config.closeDuration = closeDuration OR duration;
config.openDuration = openDuration OR duration;

基本上,如果它们未设置为默认值,则无论持续时间值是多少。即使该值已由用户设置。(例如,持续时间 = 500)

我只是想知道是否有办法简化这个?

jQuery.fn.lighthouse = function(settings) {
    var config = {
            containerSelector: 'a',
            childSelector: 'span',
            closeSelector: '.close',
            duration: 350,
            openDuration: config.duration,
            closeDuration: config.duration,
            secondaryDuration: 100,
            background: 'rgb(230, 230, 230)',
            backgroundOpacity: '0.7'
        };

    if (settings){
        config = $.extend(config, settings);
    }
}
4

1 回答 1

2

通过将可选值设置为 null,然后可以使用内联 if 语句来确定设置的值。这是 Karl-André Gagnon 和 charlietfl 答案的组合:

jQuery.fn.lighthouse = function(settings) {
    var config = {
        containerSelector: 'a',
        childSelector: 'span',
        closeSelector: '.close',
        duration: 350,
        openDuration: null,
        closeDuration: null,
        secondaryDuration: 100,
        background: 'rgb(230, 230, 230)',
        backgroundOpacity: '0.7'
    };

    if (settings){
        config = $.extend(config, settings);
    }

    config.openDuration = config.openDuration || config.duration;
    config.closeDuration = config.closeDuration || config.duration;
}
于 2014-06-12T21:07:51.817 回答