我正在尝试为 jquery 中的多个日期选择器设置不同的选项。 我的代码是这样的:
{foreach $cart->getItems() as $item}
{if $item->action->prereservation}
var disableDates = new Array();
{if $item->action->hasVariants()}
disableDates[{!$item->id}] = {$disabledDates[$item->action->id][$item->idVariant]};
{else}
disableDates[{!$item->id}] = {$disabledDates[$item->action->id]};
{/if}
if (disableDates[{!$item->id}].length !== 0) {
$(".datepicker_"+'{$item->id}').datepicker({
maxDate: new Date('{!$item->action->voucherTo|date: Y-m-d}'),
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(disableDates[{!$item->id}]) // result is undefined (but not for last iteration)
return [ disableDates[{!$item->id}].indexOf(string) == -1 ]
}
})
} else {
$(".datepicker_"+'{$item->id}').datepicker({
maxDate: new Date('{!$item->action->voucherTo|date: Y-m-d}'),
})
}
{/if}
{/foreach}
但是如果 foreach 中有多个项目,我的 js 控制台会显示错误 Cannot read property 'indexOf' of undefined for the first iteration,only last is good。有人可以帮帮我吗?
在我的代码中,我结合了模板系统 Latte 和 jquery。
这是我在浏览器中的最终代码:
var disableDates = new Array();
disableDates[777955] = ["2014-07-25","2014-07-26","2014-07-27","2014-07-28","2014-07-29","2014-07-30","2014-07-31"];
if (disableDates[777955].length !== 0) {
$(".datepicker_"+'777955').datepicker({
maxDate: new Date('2014-07-31'),
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ disableDates[777955].indexOf(string) == -1 ]
}
})
} else {
$(".datepicker_"+'777955').datepicker({
maxDate: new Date('2014-07-31'),
})
}
谢谢你的建议
最佳答案
如果你在循环中这样做,你就会不断覆盖数组!
var disableDates = new Array();
disableDates[123] = 123;
console.log(disableDates[123]); //123
var disableDates = new Array();
disableDates[456] = 456;
console.log(disableDates[123]); //undefined
将数组声明移出循环或在创建新数组之前检查它是否存在。
关于javascript - 无法读取未定义的属性 'indexOf',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911859/