AFIK,没有official resource 可以在 jQuery Datepicker 中找出禁用的日期。
然而jQuery UI Datepicker 是一个基于 Javascript 的库,总有一种解决方法。下面是我尝试过的一种解决方法。
第 1 步:
以下是在 jQuery Datepicker 中禁用日期列表的方法。
var array = ["2014-03-14", "2014-03-18", "2014-03-16", "2014-04-01"]
$('input').datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [array.indexOf(string) == -1]
},
onSelect: function (date) {
console.log(findNextDisabledDateWithinMonth(date));
}
});
现在这是我在本月内获取下一个禁用日期的方法。
第 2 步:
function findNextDisabledDateWithinMonth(date) {
var currentDate = Number(date.split('-')[2]);
var month = $('.ui-datepicker-title>.ui-datepicker-month').text(); //Number(date.split('-')[1])
var year = $('.ui-datepicker-title>.ui-datepicker-year').text(); //Number(date.split('-')[0])
var nextConsectiveDates = [];
$.each($('.ui-state-disabled').find('.ui-state-default'), function (i, value) {
var numericDate = +$(value).text();
if (currentDate < numericDate) {
nextConsectiveDates.push(numericDate);
}
});
var nextDisabledDate = nextConsectiveDates[0] + "-" + month + "-" + year;
return nextDisabledDate;
}
JSFiddle
注意: 这仅适用于所选日期的月份
方法#2
正如@Salman A 在他的comment 中提到的那样,我觉得最好的办法就是顺其自然。由于我的方法将在一个月内受到限制。
这里有一个优雅的方法来解决您的问题。
var array = ["2014-05-01", "2014-04-14", "2014-04-18", "2014-04-16"];
// Convert all those string dates into Date array
var arrayAsDateObjects = convertStringToDateObject(array);
$('input').datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [array.indexOf(string) == -1]
},
onSelect: function (date) {
alert(findNextDisabledDateWithinMonth(date).toDateString());
}
});
//To find the next exact disabled date based on the selected date
function findNextDisabledDateWithinMonth(date) {
var splitDate = date.split("-");
var selectedDate = new Date(splitDate[0], Number(splitDate[1]) - 1, splitDate[2]);
var nextDisabledDate = null;
$.each(arrayAsDateObjects, function (i, ele) {
if (selectedDate < ele) {
nextDisabledDate = ele;
return false;
} else {
nextDisabledDate = "No Disabled dates available";
}
});
return nextDisabledDate;
}
//convert all the string dates to Date object
function convertStringToDateObject(array) {
var ls = [];
$.each(array, function (i, ele) {
var splitDate = ele.split("-");
var date = new Date(splitDate[0], Number(splitDate[1]) - 1, splitDate[2]);
ls.push(date);
});
// Sort the dates in ascending order(https://stackoverflow.com/a/10124053/1671639)
ls.sort(function (a, b) {
return a - b;
});
return ls;
}
对于日期的排序,我参考了@Phrogz 's answer