jQuery UI DatePicker:禁用指定的日期

    技术2022-07-11  144

    One project I'm currently working on requires jQuery. The project also features a datepicker for requesting a visit to their location. jQuery UI's DatePicker plugin was the natural choice and it does a really nice job. One challenge I encountered was the need to prevent specific days from being picked. Here's the jQuery JavaScript I used to accomplish that.

    我目前正在研究的一个项目需要jQuery。 该项目还具有一个日期选择器,用于请求访问其位置。 jQuery UI的DatePicker插件是很自然的选择,并且做得很好。 我遇到的一个挑战是需要防止选择特定的日子。 这是我用来完成此任务的jQuery JavaScript。

    View Demo 观看演示

    jQuery JavaScript (The jQuery JavaScript)

    /* create an array of days which need to be disabled */ var disabledDays = ["2-21-2010","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"]; /* utility functions */ function nationalDays(date) { var m = date.getMonth(), d = date.getDate(), y = date.getFullYear(); //console.log('Checking (raw): ' + m + '-' + d + '-' + y); for (i = 0; i < disabledDays.length; i++) { if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1 || new Date() > date) { //console.log('bad: ' + (m+1) + '-' + d + '-' + y + ' / ' + disabledDays[i]); return [false]; } } //console.log('good: ' + (m+1) + '-' + d + '-' + y); return [true]; } function noWeekendsOrHolidays(date) { var noWeekend = jQuery.datepicker.noWeekends(date); return noWeekend[0] ? nationalDays(date) : noWeekend; } /* create datepicker */ jQuery(document).ready(function() { jQuery('#date').datepicker({ minDate: new Date(2010, 0, 1), maxDate: new Date(2010, 5, 31), dateFormat: 'DD, MM, d, yy', constrainInput: true, beforeShowDay: noWeekendsOrHolidays }); });

    The base code is taken from this forum post. You'll note that I created an array of dates in string format which also accommodates for comparing year.

    基本代码来自此论坛帖子 。 您会注意到,我以字符串格式创建了一个日期数组,该日期数组也可用于比较年份。

    View Demo 观看演示

    I'd like to see jQuery UI implement a standard way of disabling days. Their DatePicker is very nice though so I can't complain too much!

    我希望看到jQuery UI实现禁用日期的标准方法。 他们的DatePicker非常好,所以我不能抱怨太多!

    翻译自: https://davidwalsh.name/jquery-datepicker-disable-days

    相关资源:jQuery日期时间范围选择插件设置日期范围选择代码
    Processed: 0.011, SQL: 9