You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap DateTime Picker动态禁用小时功能失效问题

问题解决:Bootstrap DateTimePicker动态禁用小时失效

核心问题分析

  1. 数据类型不匹配:Laravel后端返回的小时是字符串数组(如["6", "7"]),但Bootstrap DateTimePicker的disabledHours参数要求传入数字类型数组(如[6,7]),动态传入纯字符串数组时组件无法识别,导致禁用逻辑失效。
  2. 重复初始化未销毁实例:每次切换星期调用loadPicker时,未先销毁已创建的datetimepicker实例,新配置无法覆盖旧实例的设置,组件仍沿用首次初始化的规则。

解决方案

前端代码修改

在loadPicker函数中,先销毁旧实例,再将字符串数组转为数字数组后传入:

function loadPicker(timeData) {
    // 销毁已存在的datetimepicker实例,避免配置冲突
    $('.lesson-timepicker').datetimepicker('destroy');
    
    // 将字符串数组转为数字数组,匹配组件参数要求
    const disabledHoursArray = timeData.map(hour => parseInt(hour, 10));

    $('.lesson-timepicker').datetimepicker({
        format: 'hh:mm A',
        stepping: 30,
        disabledHours: disabledHoursArray,
        icons: {
            up: 'fa fa-chevron-up',
            down: 'fa fa-chevron-down',
            previous: 'fa fa-chevron-left',
            next: 'fa fa-chevron-right'
        }
    })
}

可选:后端代码优化(减少前端转换步骤)

如果想在后端直接返回数字数组,修改Laravel的映射逻辑:

$scheduleCollection = collect($schedules)->map(function ($time) {
    return [
        (int)date("g", strtotime($time['start_time'])),
        (int)date("g", strtotime($time['end_time']))
    ];
})->flatten();

额外优化点

将moment.updateLocale的配置移到DOM初始化时只执行一次,避免重复调用:

document.addEventListener('DOMContentLoaded', function() {
    moment.updateLocale('en', {
        week: { dow: 1 } // Monday is the first day of the week
    });
    filterTime();
});

内容的提问来源于stack exchange,提问作者Lucky Person

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:11:07