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

为多个.countdown类元素设置倒计时时.html()方法无法显示内容的技术问题

解决多个倒计时元素无法显示内容的问题

我帮你定位到两个核心问题,这就是你的.html()方法失效的原因:

问题1:时间戳计算错误

你直接使用.text()获取的字符串格式时间expiry去减去now(时间戳数字),字符串和数字做减法会得到NaN,导致后续的天数、小时等计算全部无效,自然无法渲染内容。

问题2:this指向混乱

在setInterval的回调函数内部,this的指向已经不再是当前遍历的.expiry元素了,而是指向全局对象(浏览器里是window),所以$(this).closest("div").find(".countdown")根本找不到目标元素,.html()也就无从谈起。


修正后的完整代码

HTML部分保持不变:

<div>
  <div class="expiry">2021-12-10 11:12:50</div>
  <div class="countdown"></div>
</div>
<div>
  <div class="expiry">2022-09-12 07:27:34</div>
  <div class="countdown"></div>
</div>

jQuery代码修正如下:

$(".expiry").each(function () {
  // 提前保存当前.expiry元素的引用,避免setInterval里this指向变化
  const $currentExpiry = $(this);
  // 将文本格式的时间转成时间戳(毫秒数)
  const expiryTime = new Date($currentExpiry.text()).getTime();

  const timer = setInterval(function () {
    const now = new Date().getTime();
    let distance = expiryTime - now;

    // 处理倒计时结束的情况,避免出现负数
    if (distance < 0) {
      clearInterval(timer);
      $currentExpiry.closest("div").find(".countdown").html("已过期");
      return;
    }

    // 计算天、时、分、秒
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // 使用提前保存的元素引用来找到对应的.countdown并更新内容
    $currentExpiry.closest("div").find(".countdown").html(`${days}d ${hours}h ${minutes}m ${seconds}s`);
  }, 1000);
});

关键修正说明

  • 固定元素引用:在each循环里用$currentExpiry保存当前的.expiry元素,这样setInterval回调里可以直接使用这个变量找到对应的.countdown,彻底解决this指向问题。
  • 时间格式转换:把字符串时间转成Date对象再获取时间戳,确保和now的计算是有效的数字运算,不会出现NaN。
  • 新增过期处理:当倒计时结束时清除定时器,并显示“已过期”,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:02:31