考虑以下几点:
https://jsfiddle.net/Twisty/vt9Lqy1f/96/
JavaScript
$(function() {
let finalPriceObj = {
'2021-08-24': {
'newRate': "10000"
},
'2021-08-25': {
'newRate': "10000"
},
'2021-08-26': {
'newRate': "10000"
},
'2021-08-28': {
'newRate': "10000"
},
'2021-08-29': {
'newRate': "10000"
},
'2021-08-30': {
'newRate': "10000"
},
'2021-08-31': {
'newRate': "10000"
},
'2021-09-01': {},
},
missingDates = ['2021-08-27'],
datepicker = $('#datepicker'),
checkInDate = $("#checkInDate"),
checkOutDate = $("#checkOutDate"),
selectedDates = [];
function dateToString(dt) {
if (dt instanceof Date) {
return $.datepicker.formatDate("yy-mm-dd", dt);
}
return "";
}
function stringToDate(st) {
if (typeof st == "string") {
return $.datepicker.parseDate("yy-mm-dd", st);
}
return null;
}
datepicker.datepicker({
minDate: 1,
dateFormat: "yy-mm-dd",
beforeShowDay: function(date) {
var skipMissing = (selectedDates.length >= 1 ? true : false);
var show = true,
highlight = "";
if (!skipMissing && (missingDates.indexOf(dateToString(date)) >= 0)) {
show = false;
}
if (selectedDates.length == 1) {
if (date == selectedDates[0]) {
highlight = "dp-highlight";
}
}
if (selectedDates.length == 2) {
if (date == selectedDates[0]) {
highlight = "dp-highlight";
}
if (date == selectedDates[1]) {
highlight = "dp-highlight";
}
if ((date > selectedDates[0]) && (date < selectedDates[1])) {
highlight = "dp-range";
}
}
return [show, highlight];
},
onSelect: function(dString, dInst) {
if (selectedDates.length == 0) {
checkInDate.html(dString);
selectedDates.push(stringToDate(dString));
if (stringToDate(dString) < stringToDate(missingDates[0])) {
datepicker.datepicker("option", "maxDate", missingDates[0]);
}
} else if (selectedDates.length == 1) {
checkOutDate.html(dString);
selectedDates[1] = stringToDate(dString);
} else {
checkInDate.html("");
checkOutDate.html("");
selectedDates = [];
datepicker.datepicker("option", "maxDate", "");
}
datepicker.datepicker("refresh");
console.log(dString, selectedDates);
}
});
});
Array.prototype.unique = function() {
var a = this.concat();
for (var i = 0; i < a.length; ++i) {
for (var j = i + 1; j < a.length; ++j) {
if (a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
我不经常使用 MomentJS,我需要的一切都可以从 jQuery UI 获得。如果您喜欢使用它,请自行选择,只需在需要的地方进行调整。
所以你有几个不同的州要解决:
- 未选择日期
- 已选择一个日期
- 选择了两个日期
- 重置选择
用户和脚本需要知道选定的日期,所以我创建了一个数组来包含这些日期。它将包含每个选定日期的 Date 对象。这也使得执行日期比较变得更加容易。
在我们的第一个状态中,我们只想禁用missingDates,所以如果当前的date 匹配,我们就禁用它。我们将知道我们处于第一个状态,因为selectedDates 将不包含日期,长度将为0。
在我们的第二种状态中,我们将跳过缺少的日期,因为 maxDate 将被设置。我们知道我们处于第二种状态,因为已经设置了一个日期,我们正在等待下一个选择。
在我们的第三个状态中,我们选择了两个日期。我们要确保突出显示范围。
我们的最终状态,我们假设用户想要重新选择日期。