如何设置daterangepicker的全局值?

时间:2016-12-07 22:15:08

标签: javascript jquery daterangepicker bootstrap-daterangepicker

Github:Bootstrap Daterangepicker,插件来源:daterangepicker.js

我想为locale选项设置全局值。我不想每次使用它时为每个元素设置它。

以下是如何为特定元素设置daterangepicker的示例代码。

$('#demo').daterangepicker({
    "locale": {
        "format": "MM/DD/YYYY",
        "separator": " - ",
        "applyLabel": "Apply",
        "cancelLabel": "Cancel",
        "fromLabel": "From",
        "toLabel": "To",
        "customRangeLabel": "Custom",
        "weekLabel": "W",
        "daysOfWeek": [
            "Su",
            "Mo",
            "Tu",
            "We",
            "Th",
            "Fr",
            "Sa"
        ],
        "monthNames": [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
        ],
        "firstDay": 1
    },
    "startDate": "12/01/2016",
    "endDate": "12/07/2016"
}, function(start, end, label) {
  console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
});

甚至可能吗?或者我是否必须重写插件?

如果没有一些自定义修改,这是不可能的最佳方法?

2 个答案:

答案 0 :(得分:0)

Dan Grossman在2.1.26

中增加了支持
Added support for $.fn.daterangepicker.defaultOptions to set default options for all pickers on page.

让我们尝试在这里为新手进行解释。

$.fn.daterangepicker.defaultOptions = {
    locale: {
        "format": "DD/MM/YYYY",
        "separator": " - ",
        "applyLabel": "Aplicar",
        "cancelLabel": "Cancelar",
        "fromLabel": "Desde",
        "toLabel": "Hasta",
        "customRangeLabel": "Personalizado",
        "weekLabel": "W",
        "firstDay": 0,
        "daysOfWeek": ["Lu","Ma","Mi","Ju","Vi","Sa","Do"],
        "monthNames": [
            "Enero",
            "Febrero",
            "Marzo",
            "Abril",
            "Mayo",
            "Junio",
            "Julio",
            "Agosto",
            "Septiembre",
            "Octubre",
            "Noviembre",
            "Diciembre",
        ]
    }
}

$('#period').daterangepicker();

感谢@ kurdemol94

答案 1 :(得分:-1)

您可以将dateRangePickerSettings存储为全局变量

var dateRangePickerSettings = {
    locale: {...},
};

并将其引用到所有你的插件实例

$('#demo1').daterangepicker({
    "locale": dateRangePickerSettings.locale,
    "startDate": "06/01/2016",
    "endDate": "06/07/2016"
});

$('#demo2').daterangepicker({
    "locale": dateRangePickerSettings.locale,
    "startDate": "12/01/2016",
    "endDate": "12/07/2016"
});