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

HTML+JS指定日期时间后页面跳转失效问题求助

修复指定日期后自动跳转的无效问题

你当前的代码无法生效可能有几个原因,以下是对应的修复方案:

问题分析

  1. 日期格式解析歧义:new Date('2023-08-5T00:00:00')这种单数字日期的格式,部分浏览器可能无法正确解析,导致日期对象创建错误,判断逻辑失效。
  2. 脚本执行时机:脚本放在<head>中时,虽然跳转逻辑不依赖DOM,但放到<body>末尾执行更稳妥,避免潜在的环境问题。
  3. 全局对象引用不明确:直接使用location.href不如明确使用window.location.href,减少作用域歧义。

修复后的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>title</title>
</head>
<body>
    <script>
        const currentDate = new Date();
        // 使用标准两位日期格式,避免解析错误
        const targetDate = new Date('2023-08-05T00:00:00');

        if (currentDate > targetDate) {
            // 明确指向全局window对象的location
            window.location.href = './redirect.html';
        }
    </script>
</body>
</html>

额外注意事项

  • 确保redirect.html和index.html在同一目录下,否则需要调整路径(比如上级目录用../redirect.html,绝对路径用/path/to/redirect.html)。
  • 测试时可以把targetDate设置为当前时间之前的日期,比如new Date('2023-01-01T00:00:00'),快速验证跳转是否生效。
  • 更可靠的日期构造方式:使用new Date(年, 月份索引, 日, 时, 分),注意月份索引从0开始(8月对应7),例如new Date(2023, 7, 5, 0, 0),这种方式不会出现解析歧义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:40:11