我正在使用jquery和jquery ui 1.8.7。我在页面加载时创建一个内联日期选择器,然后在我的ajax成功函数中,我调用$('#mydiv')。datepicker('refresh'); (我将在下面发布代码)。
如果数据已从ajax返回(例如刷新),则beforeShowDay调用highlightDays()函数。我知道在一切都崩溃之前我正在使用正确的数据两次点亮highlightDays并且我得到一个错误“TypeError:无法读取未定义的属性0”。
似乎事件数组在一段时间后被破坏了,但我不太了解ajax真正说出发生了什么。任何人都可以指出我正确的方向来解决这个问题吗?
function highlightDays(date) {
var day = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
console.log(typeof(events)); // This will return as an object twice before throwing an the above mentioned error
if($.inArray(day, events) !== -1) {
return new Array(true, '');
} else {
return new Array(false, '');
}
}
function getEventData() {
return $.ajax({
url: Drupal.settings.basePath + 'correct_path',
data: search+'&path='+window.location.pathname,
dataType: 'json',
type: 'POST',
success: function(data, textStatus, jqXHR) {
// save our returned data
events = new Object();
events = data;
$('#mydiv').datepicker("refresh");
}
});
}
function createDatepicker() {
// Attach datepicker to the parent div so it returns as
// inline.
$('#mydiv').datepicker({
dateFormat: 'yy-mm-dd',
speed: 'immediate',
altField: '#edit-date-filter-value-datepicker-popup-1',
beforeShowDay: function(date) {
if(typeof (_event_days) === 'undefined') {
return new Array(true, '');
} else {
highlightDays(date);
}
},
});
$('#myinput').hide();
}
getEventData();
createDatepicker();
答案 0 :(得分:0)
以下代码最终为我工作。两大差异。重新设计highlightDays函数,并将从ajax调用返回的所有数据添加到全局事件数组中,稍后将在highlightDays中使用。
var events = [];
function highlightDays(date) {
var dayClass = [true, ''];
var date = $.datepicker.formatDate('yy-mm-dd', new Date(date));
$.each(events, function(key, value) {
if (date === value[0]) {
dayClass = [true, "ui-state-highlight"];
return dayClass;
} else {
return dayClass;
}
});
return dayClass;
}
function getEventData() {
return $.ajax({
url: 'myurl',
data: search+'&path='+window.location.pathname,
dataType: 'json',
type: 'POST',
success: function(data, textStatus, jqXHR) {
$.each(data, function (index, value) {
events.push([value]);
});
// popup is the date input field
// attaching datepicker to the parent div makes
// it an inline picker
popup.parent().datepicker('refresh');
}
});
}
function createDatepicker() {
popup.parent().datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: highlightDays
});
popup.hide();
}
function getSearchString() {
// Return a search string to pass to the ajax call
var search = window.location.search;
if(search !== '') {
while(search.charAt(0) === '?') {
// remove the leading question mark in the search string
search = search.substr(1);
}
}
return search;
}
// If our popup selector exists, create the datepicker and get event data
if (popup.length) {
var search = getSearchString();
getEventData();
createDatepicker();
}