【问题标题】:datepicker Error = Uncaught TypeError: Cannot read property '0' of undefineddatepicker 错误 = 未捕获的类型错误:无法读取未定义的属性“0”
【发布时间】:2013-05-22 17:44:16
【问题描述】:

无法让 jQueryUI 日期选择器选项 beforeShowDay 工作。

我尝试了找到的不同帮助主题,但无法正常工作。

我收到此错误

未捕获的类型错误:无法读取未定义的属性“0”

这是我的 JS。但它似乎不起作用

<script type="text/javascript">
jQuery(document).ready(function () {
    var your_dates = [new Date(13, 5, 5), new Date(13, 5, 10)];
    jQuery("div#event-calender").datepicker({
        beforeShowDay: function (date) {
            if (jQuery.inArray(date.toString(), your_dates) != -1) {
                return [true, 'highlight'];
            }
        }
    });
});
</script>

【问题讨论】:

    标签: jquery jquery-ui jquery-ui-datepicker


    【解决方案1】:

    您需要始终返回一个数组,而不仅仅是在条件匹配时。

    来自documentation

    演出前

    类型:函数(日期日期)

    以日期为参数的函数必须返回一个数组

    jQuery(document).ready(function () {
        var your_dates = [new Date(13, 5, 5), new Date(13, 5, 10)];
        jQuery("div#event-calender").datepicker({
            beforeShowDay: function (date) {
                var arr;
                if (jQuery.inArray(date.toString(), your_dates) != -1) {
                    arr = [true, 'highlight'];
                }else {
                    arr = [true, ''];
                }
                return arr;
            }
        });
    });
    

    FIDDLE

    【讨论】:

    • 谢谢,一个非常明显的问题,节省了我一些调试时间来实际找到问题所在,因为 js 错误没有显示文件 +1 的确切行 :)
    【解决方案2】:

    演出前
    以日期为参数且必须返回数组的函数 与:

    • true/false 表示此日期是否可以通过 CSS 选择
    • 类名添加到日期的单元格或“”作为默认值
    • 显示此日期的可选弹出工具提示

    在日期选择器中每天调用该函数之前 显示

    将您的 beforeShowDay 更改为

    beforeShowDay: function (date) {
        if (jQuery.inArray(date.toString(), your_dates) != -1) {
            return [true, 'highlight'];
        } else {
            return [true, ''];
        }
    }
    

    编辑
    your_dates 更改为

    var your_dates = [new Date(2013,5,5).toString(), new Date(2013,5,10).toString()];
    

    或使用类似的东西代替jQuery.inArray(...)

    var found = your_dates.filter(function(d) {
                    return date.getTime() === d.getTime();
                }).length > 0;
    
    return [true, (found ? 'highlight' : '')];
    

    【讨论】:

    • 这有帮助,谢谢。但是我所有的元素都“不突出”。你知道这个问题是什么吗?我应该选择其他日期格式吗?
    • 这真的是你期待的日期吗new Date(13, 5, 5) == "05. June, 1913"
    • 不,我的数组现在看起来像这样 var your_dates = [new Date(2013,05,05), new Date(2013,05,10)]; 但仍然没有人得到高光课
    猜你喜欢
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多