JavaScript如何对比当前时间与div ID中H:MM格式的时间值
时间对比逻辑修正方案
现有代码核心错误
- 取值语法错误:
$(this).attr("id")执行后已经直接返回id属性的字符串值,后续链式调用.val()属于无效写法——.val()仅用于获取input、select等表单元素的用户输入值,普通DOM元素属性通过attr()获取后无需额外调用取值方法,该写法会直接抛出JS错误阻断执行。 - 对比逻辑错误:直接对
H:MM格式的字符串做大小比较会触发字典序比对,结果完全不符合时间先后逻辑,比如字符串"9:00"和"11:00"对比时,由于首字符"9"的ASCII码大于"1",会被误判为9点比11点更晚。 - 类名切换逻辑遗漏:状态切换时没有清除元素上已有的其他状态类,容易出现单个元素同时挂载
past/present/future多个类的样式冲突问题。
修正后代码
既然已经引入moment库,统一将两个时间转换为「当日0点至今的分钟数」做纯数值对比,从根源上避免时间格式带来的对比误差:
// 获取当前时间对应的当日分钟数 const currentTotalMinutes = moment().hours() * 60 + moment().minutes(); $(".time-div").each(function () { const $currentEl = $(this); // 读取元素ID上存储的时间字符串 const slotTimeStr = $currentEl.attr("id"); // 用moment解析槽位时间,转成对应的当日分钟数 const slotMoment = moment(slotTimeStr, "H:mm"); const slotTotalMinutes = slotMoment.hours() * 60 + slotMoment.minutes(); // 先清空所有状态类,避免类名叠加 $currentEl.removeClass("past present future"); // 纯数值对比,结果稳定准确 if (slotTotalMinutes === currentTotalMinutes) { $currentEl.addClass("present"); } else if (slotTotalMinutes > currentTotalMinutes) { $currentEl.addClass("future"); } else { $currentEl.addClass("past"); } });
场景适配优化
如果你的时间槽代表1小时的时间段(比如id为11:00的div对应11:00-12:00的时间区间),可以把精确匹配的判断逻辑改成区间判断,更符合日程类场景的实际需求:
// 替换原有相等判断逻辑即可 if (currentTotalMinutes >= slotTotalMinutes && currentTotalMinutes < slotTotalMinutes + 60) { $currentEl.addClass("present"); } else if (slotTotalMinutes > currentTotalMinutes) { $currentEl.addClass("future"); } else { $currentEl.addClass("past"); }
内容的提问来源于stack exchange,提问作者Marlowepdx
相关产品推荐
相关产品推荐

