【问题标题】:Restrict month view in month-year datepicker限制月-年日期选择器中的月视图
【发布时间】:2014-01-01 09:53:29
【问题描述】:

我正在使用 jQuery 月份和年份选择器(我隐藏了日期选择器的日期部分)。

在这个日历中,我只需要在月份选择中显示一月、三月、四月和九月。有没有内置的方法?

$('.datepicker_month_year').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'M yy',
    beforeShow: function (input, inst) {
        $(inst.dpDiv).addClass('calendar-off');
    },
    onClose: function (dateText, inst) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    }
});

【问题讨论】:

标签: jquery jquery-ui datepicker


【解决方案1】:

您可以考虑在 beforeShowDay 中检查之前加载的数组中显示的月份是否存在。

代码:

monthArray = [0, 2, 3, 8]

$(function () {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'M yy',
        beforeShowDay: function (date) {
            //getMonth()  is 0 based
            if ($.inArray(date.getMonth(), monthArray) > -1) {
                return [true, ''];
            }
            return [false, ''];
        }
    });

});

演示:http://jsfiddle.net/IrvinDominin/4Vz6b/

编辑

您每年仅使用 css hack 进行显示,在这种情况下,您希望限制月份的显示。

如果您显示日期,第一个解决方案会起作用,但事实并非如此。

您可以考虑使用.ui-datepicker-month 类从选择中隐藏不允许的选项,因为我使用了focus 事件有任何 afterShow 事件(或类似事件)。在函数中,我检查显示的月份是否在允许列表中。

代码:

monthArray = [0, 2, 3, 8]

$(function () {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'M yy',
        beforeShow: function (input, inst) {
            $(inst.dpDiv).addClass('calendar-off');
        },
        onClose: function (dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    }).focus(function () {
        $($.grep($("select.ui-datepicker-month option"),

        function (n, i) {
            return $.inArray(parseInt(n.value, 10), monthArray) > -1 ? false : true;
        })).hide()
    });;
});

演示:http://jsfiddle.net/IrvinDominin/Q3f29/

【讨论】:

  • 这个代码没问题,如果它是一个日期选择器,在我的代码中它的月份和年份选择器..我需要限制月份选择下拉列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
相关资源
最近更新 更多