【问题标题】:jQuery UI Datepicker won't render second month in restricted selectionjQuery UI Datepicker 不会在受限选择中呈现第二个月
【发布时间】:2014-12-12 01:22:50
【问题描述】:

我有一个小提琴:http://jsfiddle.net/4w846rf3/

我将一组日期传递给 jQuery UI 的日期选择器。对于这些日期,我想限制当前日历,以便只能选择提供的日期。经过大量研究,我发现beforeShowDay 函数将有助于限制天数,但我所经历的并不正确。当前月份的天数将呈现正确的受限天数,但下个月不会。

var availableDates = [
    "12-22-2014", 
    "12-13-2014", 
    "12-27-2014", 
    "01-17-2015", 
    "01-24-2015"
];

function available(date) {
  dmy =  (date.getMonth()+1) + "-" + date.getDate() + "-" + date.getFullYear();
  console.log(dmy+' : '+($.inArray(dmy, availableDates)));
  if ($.inArray(dmy, availableDates) != -1) {
    return [true, "","Available"];
  } else {
    return [false,"","unAvailable"];
  }
}

$('input').datepicker({beforeShowDay: available})

正确渲染 12 月:

和一月错误:

【问题讨论】:

  • 查看你的 console.log 输出。 1-17-201501-17-2015 不同。
  • 我建议你使用$.datepicker.formatDate()而不是连接数字。

标签: javascript jquery jquery-ui date datepicker


【解决方案1】:

你可以这样做:

var availableDates = [
  "12-22-2014", 
  "12-13-2014", 
  "12-27-2014", 
  "01-17-2015", 
  "01-24-2015"
];

function checkAvailability(date){
  var dateString = $.datepicker.formatDate('mm-dd-yy', date);
  return [availableDates.indexOf(dateString) !== -1]
}

$('input').datepicker({
  beforeShowDay: checkAvailability
});

正如 Barmar 所建议的,这利用了 $.datepicker.formatDate(),顾名思义,它将日期格式化为具有指定格式的字符串值。

一旦我们有了一个格式与数组中相同的日期字符串,使用beforeShowDay 选项就很简单了,只有当日期字符串与其中一个匹配时才返回true你已经指定了。

formatDate() 方法是日期选择器的实用功能之一。 你可以在这里阅读:http://api.jqueryui.com/datepicker/#utility-functions

演示

var availableDates = [
  "12-22-2014", 
  "12-13-2014", 
  "12-27-2014", 
  "01-17-2015", 
  "01-24-2015"
];

function checkAvailability(date){
  var dateString = $.datepicker.formatDate('mm-dd-yy', date);
  return [availableDates.indexOf(dateString) !== -1]
}

$('input').datepicker({
  beforeShowDay: checkAvailability
});
<link href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>


<input type="text"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多