jQuery datepicker高亮范围循环

时间:2014-03-11 23:03:03

标签: javascript jquery jquery-ui datepicker jquery-ui-datepicker

我想在jQuery日期选择器上突出显示日期范围。

  var dates = new Array();
  dates[0] = [new Date(2014,2,23), new Date(2014,2,30)];
  dates[1] = [new Date(2014,2,13), new Date(2014,2,20)];

  $(function() {
    $('#datepicker').datepicker({
        numberOfMonths: 1,
        minDate: '-0m',
        beforeShowDay: function (date) {
            for (i=0;i<dates.length;i++) {
                var date1 = dates[i][0];
                var date2 = dates[i][1];
                return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
            }
        }
    })
  });

由于只能看到一个范围,因此上述方法无效。如何进行循环以突出多个范围?谢谢你的帮助!

Fiddle

2 个答案:

答案 0 :(得分:1)

尝试

var dates = new Array();
dates[0] = [new Date(2014, 2, 23), new Date(2014, 2, 30)];
dates[1] = [new Date(2014, 2, 13), new Date(2014, 2, 20)];

$(function () {
    $('#datepicker').datepicker({
        numberOfMonths: 1,
        minDate: '-0m',
        beforeShowDay: function (date) {
            var flag = false,
                date1, date2, i;
            for (i = 0; i < dates.length; i++) {
                date1 = dates[i][0];
                date2 = dates[i][1];

                flag = (!date1 || date.getTime() >= date1.getTime()) && (!date2 || date.getTime() <= date2.getTime())
                if (flag) {
                    break;
                }
            }
            return [true, flag ? "dp-highlight" : ""];
        }
    })
});

演示:Fiddle

答案 1 :(得分:1)

问题是你在循环中有回归 因此,在第一个循环结束时,函数返回true或false

您应该执行以下操作:

var dates = new Array();
  dates[0] = [new Date(2014,2,23), new Date(2014,2,30)];
  dates[1] = [new Date(2014,2,13), new Date(2014,2,20)];

  $(function() {
    $('#datepicker').datepicker({
        numberOfMonths: 1,
        minDate: '-0m',
        beforeShowDay: function (date) {
            var bool = true;
            for (i=0;i<dates.length;i++) {
                var date1 = dates[i][0];
                var date2 = dates[i][1];
                bool = bool && date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : "";
            }
            return bool;
        }
    })
  });