我使用easepick Javascript插件生成一个日期范围选择器。它看起来像这样:
<script src="https://cdn.jsdelivr.net/npm/@easepick/bundle@1.2.1/dist/index.umd.min.js"></script>
<input id="datepicker"/>
<script>
const DateTime = easepick.DateTime;
const bookedDates = [
'2023-04-02',
['2023-04-06', '2023-04-11'],
'2023-04-18',
'2023-04-19',
'2023-04-20',
'2023-04-25',
'2023-04-28',
].map(d => {
if (d instanceof Array) {
const start = new DateTime(d[0], 'YYYY-MM-DD');
const end = new DateTime(d[1], 'YYYY-MM-DD');
return [start, end];
}
return new DateTime(d, 'YYYY-MM-DD');
});
const picker = new easepick.create({
element: document.getElementById('datepicker'),
css: [
'https://cdn.jsdelivr.net/npm/@easepick/bundle@1.2.1/dist/index.css',
'https://easepick.com/css/demo_hotelcal.css',
],
plugins: ['RangePlugin', 'LockPlugin'],
RangePlugin: {
tooltipNumber(num) {
return num - 1;
},
locale: {
one: 'night',
other: 'nights',
},
},
LockPlugin: {
minDate: new Date(),
minDays: 2,
inseparable: true,
filter(date, picked) {
if (picked.length === 1) {
const incl = date.isBefore(picked[0]) ? '[)' : '(]';
return !picked[0].isSame(date, 'day') && date.inArray(bookedDates, incl);
}
return date.inArray(bookedDates, '[)');
},
},
autoApply: false,
onApply(dates) {
console.log(dates);
}
});
</script>
但是用户似乎无法选择包含在bookedDates
数组中的结束日期。既然它当然应该有可能有相同的结帐日期作为另一个用户选择作为签入日期,我如何修改我的filter
在LockPlugin
允许这一点?
要修改LockPlugin中的过滤器以允许用户选择已被另一个用户预订的结束日期,您可以更新filter()方法中的条件语句,以检查所选日期范围是否与任何已预订的日期重叠。
下面是一个更新的filter()方法,用于检查日期范围重叠:
LockPlugin: {
minDate: new Date(),
minDays: 2,
inseparable: true,
filter(date, picked) {
if (picked.length === 1) {
const incl = date.isBefore(picked[0]) ? '[)' : '(]';
return !picked[0].isSame(date, 'day') && date.inArray(bookedDates, incl);
}
// Check for overlap with any booked date range
for (let i = 0; i < bookedDates.length; i++) {
const bd = bookedDates[i];
const overlap = picked[0].isBetween(bd[0], bd[1], 'day', '[]') ||
picked[1].isBetween(bd[0], bd[1], 'day', '[]');
if (overlap) {
return true;
}
}
return false;
},
},
这个新的filter()方法检查用户选择的日期范围和任何预订的日期范围之间的重叠。如果有重叠,则返回true,这将阻止用户选择该日期范围。
注意,这个实现假设bookedDates只包含日期范围(即,具有两个DateTime对象的数组)。如果bookedDates也可以包含单个日期,您可能需要修改循环以适当地处理这些情况。