如何将课程计时器的内置Schedule改为读取外部Schedule.txt文件
解决方案
1. 准备外部Schedule.txt文件
将原代码中内置的schedule对象内容完整复制到Schedule.txt文件中,确保内容为标准JSON格式(所有键名、字符串使用双引号,逗号分隔正确,无多余尾逗号)。文件示例结构如下:
{ "Monday": [ { "class": "1/5", "start": "08:30", "end": "09:54" }, { "class": "2/6", "start": "10:00", "end": "11:24" } ], "Tuesday": [ { "class": "1/5", "start": "08:30", "end": "10:03" } ] // 其余日期内容与原代码一致 }
2. 修改HTML/JavaScript代码
移除原代码中内置的schedule常量,替换为异步读取外部文件的逻辑,并调整计时逻辑的启动时机,确保数据加载完成后再执行:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Class Timer</title> <style> body { font-family: Arial, sans-serif; text-align: center; } </style> </head> <body> <h1>Class Timer</h1> <p id="class-info"></p> <p id="countdown"></p> <script> let schedule; // 全局变量存储日程数据 // 读取外部日程文件 fetch('Schedule.txt') .then(response => { if (!response.ok) throw new Error('日程文件加载失败'); return response.json(); }) .then(data => { schedule = data; updateTimer(); // 加载成功后立即更新显示 setInterval(updateTimer, 1000); // 启动每秒刷新的定时器 }) .catch(error => { document.getElementById('class-info').textContent = `错误: ${error.message}`; console.error(error); }); // 计算下一节课的逻辑 function calculateNextClass() { if (!schedule) return { class: "加载中...", time: 0 }; const now = new Date(); const dayOfWeek = now.toLocaleString('en-US', { weekday: 'long' }); const currentTime = now.getHours() * 60 + now.getMinutes(); const classesToday = schedule[dayOfWeek]; if (!classesToday) return { class: "今日无课程", time: 0 }; for (let i = 0; i < classesToday.length; i++) { const classStart = convertToMinutes(classesToday[i].start); if (classStart > currentTime) { const timeUntilNextClass = classStart - currentTime; return { class: classesToday[i].class, time: timeUntilNextClass }; } } return { class: "今日课程已结束", time: 0 }; } // 时间格式转换函数 function convertToMinutes(timeString) { const [hours, minutes] = timeString.split(":").map(Number); return hours * 60 + minutes; } // 更新计时器显示 function updateTimer() { const nextClass = calculateNextClass(); const hours = Math.floor(nextClass.time / 60); const minutes = nextClass.time % 60; const seconds = 60 - new Date().getSeconds(); document.getElementById("class-info").textContent = `下一节课: ${nextClass.class}`; document.getElementById("countdown").textContent = `剩余时间: ${hours}h ${minutes}m ${seconds}s`; } </script> </body> </html>
关键修改说明
- 用
fetchAPI异步加载外部文件,避免同步加载导致的阻塞或报错 - 将
schedule改为全局变量,确保后续计时逻辑能访问到数据 - 添加加载状态提示和错误捕获,避免数据未加载完成时出现异常
- 调整定时器启动时机,仅在数据加载成功后才启动计时
注意事项
- 确保
Schedule.txt与HTML文件放在同一目录下 - 本地直接打开HTML文件时,部分浏览器会因跨域限制无法加载本地文件,建议使用本地服务器(如VS Code的Live Server插件)运行
- 检查
Schedule.txt的JSON格式是否正确,格式错误会导致加载失败
内容的提问来源于stack exchange,提问作者Nathan Flood
相关产品推荐
相关产品推荐

