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

请假表单按假型限制日期天数的JS逻辑异常排查

问题分析与修复

你的代码问题出在条件判断逻辑错误:原else if中,前两个假型(leave for blood donation - two days allowed、test2 - two days allowed)没有绑定天数限制判断,只要选中这两个假型,不管申请天数多少,都会触发提示;同时第三个条件的括号嵌套错误,进一步导致逻辑混乱。

另外,直接用硬编码的字符串匹配假型容易出错(比如拼写、空格差异),建议用数组统一管理需要限制的假型,更易维护。

修复后的JavaScript代码

const form = document.querySelector('#leave-form');
form.addEventListener('submit', function(event) {
    const startDate = new Date(document.querySelector('#startdate').value);
    const endDate = new Date(document.querySelector('#tilldate').value);
    const leavetype = document.querySelector('#leavetype').value.trim();
    
    // 计算包含起止日期的天数:(结束-开始)/毫秒转天 +1
    const daysRequested = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;

    // 先判断日期合法性
    if (endDate < startDate) {
        alert('结束日期不能早于开始日期');
        event.preventDefault();
    } 
    // 判断是否是限制2天的假型,且申请天数超过2
    else {
        // 把所有需要限制2天的假型放在数组里,方便后续维护
        const twoDayLimitLeaves = [
            'leave for blood donation - two days allowed',
            'test2 - two days allowed',
            'leave for marrage - two days allowed'
        ];
        // 检查当前假型是否在限制列表中,且天数超过2
        if (twoDayLimitLeaves.includes(leavetype) && daysRequested > 2) {
            alert('该类型假期最多可申请2天');
            event.preventDefault();
        }
    }
});

额外注意事项

  • 确保MySQL表leavestypes中的leavetype字段值,和你代码中数组里的字符串完全一致(包括大小写、空格、拼写,比如你原代码中marrage是拼写错误,若数据库里是正确的marriage,要同步修正)。
  • 日期计算用Math.ceil避免因为时区问题导致天数计算偏差(比如跨时区的日期转换可能出现小数天数)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:07:47