救命! 如何在月更改后的UI datepicker中启用日期?
在我的情况下:
我想要从ajax调用启用的日子。 当我改变这个月的时候,我读了一个叫做ajax的xml文件,并得到那个月的日子。如何实现它?
非常感谢你!!
用于保存日期的数组变量:
var $daysWithRecords = new Array()
加载xml文件的函数:
function getDays(year,month){ $.ajax({ type: "GET", url: "users.xml", dataType: "xml", success:function(msg) { initDaysArray( $(msg) , year , month ); } }); }
函数初始化days数组:
function initDaysArray( $xml , year , month ) { //alert(year+'-'+month); var dateToFind = year+'-'+month; var $myElement = $xml.find( 'user[id="126"]' ); dates = ''; $myElement.find('whDateList[month="'+dateToFind+'"]').find('date').each(function(){ $daysWithRecords.push(dateToFind+$(this).text()); dates += $(this).text() + ' '; }); console.log(dates); console.log($daysWithRecords.length) }
函数使数组变量中的日期可用:
function checkAvailability(avalableDays){ var $return=false; var $returnclass ="unavailable"; $checkdate = $.datepicker.formatDate('yy-mm-dd', avalableDays); for(var i = 0; i < $daysWithRecords.length; i++){ if($daysWithRecords[i] == $checkdate){ $return = true; $returnclass= "available"; } } return [$return,$returnclass]; }
datepicker部分代码加载和显示天[ 注意:我使用的是datepicker的内联模式 ]
$('#div').datepicker({ dateFormat: 'yy-mm-dd',defaultDate: '2010-09-01' , onChangeMonthYear: function(year, month, inst) { console.log(year); console.log(month); getDays(year,month); } , beforeShowDay: checkAvailability });
最后我的xml文件:
john 01 05 21 01 05 06 07 08 09 12 13 14 16 18 19 21 22 23 24 25 26 29
非常感谢你!!
问题是这里的日期格式,当你将它们出现的日期存储为2010-1001
而不是2010-10-01
,所以改变这个:
$daysWithRecords.push(dateToFind+$(this).text());
对此:
$daysWithRecords.push(dateToFind+"-"+$(this).text());
你可以看到它在这里工作 。
这是一个整体更优化的版本,更少的循环和没有无限增长的数组:
var daysWithRecords = []; function initDaysArray( $xml , year , month ) { var d = year+'-'+month; daysWithRecords = $xml.find('user[id="126"] whDateList[month="'+d+'"] date').map(function() { return d+"-"+$(this).text(); }).get(); } function checkAvailability(availableDays) { var checkdate = $.datepicker.formatDate('yy-mm-dd', availableDays); for(var i = 0; i < daysWithRecords.length; i++) { if(daysWithRecords[i] == checkdate){ return [true, "available"]; } } return [false, ""]; } $('#div').datepicker({ dateFormat: 'yy-mm-dd', defaultDate: '2010-09-01', onChangeMonthYear: getDays, beforeShowDay: checkAvailability });
你可以在这里测试一下 。