【问题标题】:Cannot read property 'indexOf' of undefined无法读取未定义的属性“indexOf”
【发布时间】:2014-09-14 17:14:49
【问题描述】:

我正在尝试为 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 控制台显示错误无法读取第一次迭代未定义的属性 'indexOf',只有最后一个是好的。有人可以帮帮我吗?

在我的代码中,我结合了模板系统 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'),
            })
        }

感谢您的建议

【问题讨论】:

  • 在返回之前,执行console.log(disableDates[{!$item->id}]) _ 我的猜测是,计算结果为undefined
  • 我们还需要您的 getItems 函数
  • 我已经用浏览器中的最终代码编辑了我的问题
  • @karthikr:你说得对,但如果我在浏览器中查看最终代码,我认为它看起来不错

标签: javascript jquery nette


【解决方案1】:

如果您在循环中执行此操作,则会继续覆盖数组!

var disableDates = new Array();
disableDates[123] = 123;
console.log(disableDates[123]);  //123

var disableDates = new Array();
disableDates[456] = 456;
console.log(disableDates[123]);  //undefined

将数组声明移出循环或在创建新数组之前检查它是否存在。

【讨论】:

  • 但是每次在不同的索引中,因为$item->id是唯一的
【解决方案2】:

可以先测试字符串,再使用indexOf,例如:

var mydate;
for(i=0; i<mydate.length; i++) {
    if( mydate[i] ) {
        if(mydate[i].indexOf("some") {
              alert("OK");
        }
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 2021-08-22
    • 1970-01-01
    • 2022-09-27
    相关资源
    最近更新 更多