可以使 jQuery UI Datepicker 禁用周六和周日(和节假日)吗?

我使用日期选择器来选择约会日期.我已经将日期范围设置为仅下个月.这很好用.我想从可用选项中排除周六和周日.这可以做到吗?如果有,怎么做?

I use a datepicker for choosing an appointment day. I already set the date range to be only for the next month. That works fine. I want to exclude Saturdays and Sundays from the available choices. Can this be done? If so, how?

推荐答案

beforeShowDay 选项,它接受一个函数为每个日期调用,如果允许日期返回 true 或 false如果不是.来自文档:

There is the beforeShowDay option, which takes a function to be called for each date, returning true if the date is allowed or false if it is not. From the docs:

演出前

该函数将日期作为参数,并且必须返回一个 [0] 等于 true/false 的数组,指示此日期是否可选,并且 1 等于 CSS 类名称或 '' 用于默认演示.日期选择器中的每一天都会在显示之前调用它.

The function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable and 1 equal to a CSS class name(s) or '' for the default presentation. It is called for each day in the datepicker before is it displayed.

在日期选择器中显示一些国定假日.

Display some national holidays in the datepicker.

$(".selector").datepicker({ beforeShowDay: nationalDays})   

natDays = [
  [1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'],
  [4, 27, 'za'], [5, 25, 'ar'], [6, 6, 'se'],
  [7, 4, 'us'], [8, 17, 'id'], [9, 7, 'br'],
  [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']
];

function nationalDays(date) {
    for (i = 0; i < natDays.length; i++) {
      if (date.getMonth() == natDays[i][0] - 1
          && date.getDate() == natDays[i][1]) {
        return [false, natDays[i][2] + '_day'];
      }
    }
  return [true, ''];
}

存在一个名为 noWeekends 的内置函数,可防止选择周末.

One built in function exists, called noWeekends, that prevents the selection of weekend days.

$(".selector").datepicker({ beforeShowDay: $.datepicker.noWeekends })

<小时>

要将两者结合起来,您可以执行以下操作(假设上面的 nationalDays 函数):

$(".selector").datepicker({ beforeShowDay: noWeekendsOrHolidays})   

function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
    if (noWeekend[0]) {
        return nationalDays(date);
    } else {
        return noWeekend;
    }
}

更新:请注意,从 jQuery UI 1.8.19 开始,beforeShowDay 选项 还接受一个可选的第三个参数,一个弹出工具提示

Update: Note that as of jQuery UI 1.8.19, the beforeShowDay option also accepts an optional third paremeter, a popup tooltip

相关文章