如何设置 Datetimepicker 的默认设置?

How do I set default settings for Datetimepicker?

我使用 Bootstrap 日期时间选择器设置了多个日历输入:http://eonasdan.github.io/bootstrap-datetimepicker/

我创建了一个包含一些覆盖的对象:

DatetimepickerDefaults = {
    icons: {
        time: 'fa fa-clock-o',
        date: 'fa fa-calendar',
        up: ' fa fa-angle-up',
        down: 'fa fa-angle-down',
        previous: 'fa fa-angle-left',
        next: 'fa fa-angle-right',
        today: 'fa fa-crosshairs',
        clear: 'fa fa-trash',
        close: 'fa fa-times'
    }
}

我想应用到所有日历输入。所以现在当我想初始化我写的插件时:

$('#datetimepicker1').datetimepicker(DatetimepickerDefaults);

问题是一些输入需要一些特殊设置,比如格式:'LT' 所以当我初始化它们时,我写:

$('#datetimepicker3').datetimepicker({
    icons: {
        time: 'fa fa-clock-o',
        date: 'fa fa-calendar',
        up: ' fa fa-angle-up',
        down: 'fa fa-angle-down',
        previous: 'fa fa-angle-left',
        next: 'fa fa-angle-right',
        today: 'fa fa-crosshairs',
        clear: 'fa fa-trash',
        close: 'fa fa-times'
    },
    format: 'LT'
});

所以我不得不再次重复这个默认设置。有没有办法让它成为所有插件实例的默认值?

您可以将其设置为如下函数:

function.DatetimepickerDefaults = function(field, value) {
    var retVal = {
    icons: {
        time: 'fa fa-clock-o',
        date: 'fa fa-calendar',
        up: ' fa fa-angle-up',
        down: 'fa fa-angle-down',
        previous: 'fa fa-angle-left',
        next: 'fa fa-angle-right',
        today: 'fa fa-crosshairs',
        clear: 'fa fa-trash',
        close: 'fa fa-times'
    }};
    if (field) {
        retVal[field] = value;
    }
    return retVal;
}

并像这样使用它:

$('#datetimepicker1').datetimepicker(DatetimepickerDefaults());
$('#datetimepicker2').datetimepicker(DatetimepickerDefaults("format", "LT"));
$('#datetimepicker2').datetimepicker(DatetimepickerDefaults("format", "LT2"));
//And etc...

您可以使用列表来获取更多值,希望对您有所帮助

这是 @webmaster's , taking advantage of jQuery.extend() 方法的更紧凑和方便的版本。

// defaults
function DatetimepickerDefaults(opts) {
    return $.extend({},{
        sideBySide: true,
        ignoreReadonly: true,
        showClose: true,
        toolbarPlacement: 'top'
    }, opts);
}

// usage
$('#datetimepicker2').datetimepicker(DatetimepickerDefaults({
    sideBySide: false,
    showClear: true
}));

您可以再次为对象提供设置,这些设置将合并并在必要时覆盖默认设置。