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

求助:基于AJAX数据的Handlebars倒计时实现(无jQuery库)

解决Handlebars模板中实现纯JS倒计时的方案

我来帮你搞定这个问题!既然公司网络屏蔽了外部倒计时库,我们完全可以用纯JavaScript实现倒计时功能,再配合你现有的AJAX+Handlebars流程来完成。下面是具体步骤:

1. 编写纯JS倒计时函数

这个函数接收DOM元素和目标毫秒时间戳,负责计算剩余时间并每秒更新元素内容:

function startCountdown(element, targetTimestamp) {
  // 将毫秒时间戳转为Date对象
  const targetDate = new Date(targetTimestamp);
  
  // 每秒执行一次倒计时更新
  const countdownInterval = setInterval(() => {
    const now = new Date();
    const timeDiff = targetDate - now;
    
    // 若目标时间已过,停止倒计时并更新提示
    if (timeDiff <= 0) {
      clearInterval(countdownInterval);
      element.textContent = "已执行";
      return;
    }
    
    // 计算剩余的天、时、分、秒
    const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
    
    // 格式化显示,补零保证两位数字
    element.textContent = `${days}天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }, 1000);
  
  // 初始化时立即执行一次,避免等待1秒才显示内容
  const initialDiff = targetDate - new Date();
  if (initialDiff > 0) {
    const initDays = Math.floor(initialDiff / (1000 * 60 * 60 * 24));
    const initHours = Math.floor((initialDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const initMinutes = Math.floor((initialDiff % (1000 * 60 * 60)) / (1000 * 60));
    const initSeconds = Math.floor((initialDiff % (1000 * 60)) / 1000);
    element.textContent = `${initDays}天 ${initHours.toString().padStart(2, '0')}:${initMinutes.toString().padStart(2, '0')}:${initSeconds.toString().padStart(2, '0')}`;
  } else {
    element.textContent = "已执行";
  }
}

2. 修改AJAX回调,渲染后初始化倒计时

在你现有的getScheduledTasks函数中,Handlebars渲染完成后,遍历所有带data-countdown属性的元素,调用上面的倒计时函数:

function getScheduledTasks(URL_address){
 $.ajax({
 url: URL_address,
 success: function(data){
 var source = $("#scheduled-task").html();
 var template = Handlebars.compile(source);
 $('.scheduledBody').append(template(data));
 
 // 遍历所有倒计时元素,初始化倒计时
 $('.scheduledBody [data-countdown]').each(function() {
   // 获取data属性中的毫秒时间戳
   const targetTime = parseInt($(this).data('countdown'), 10);
   // 启动倒计时
   startCountdown(this, targetTime);
 });
 },
 error: function(data) {
 console.log('error', data);
 }
 });
}

3. 保持现有HTML/Handlebars模板不变

你的模板已经正确把timeSs(毫秒时间戳)放到了data-countdown属性中,不需要修改:

<table class="table">
 <thead class="thead-dark">
 <tr>
 <th scope="col">Name</th>
 <th scope="col">Type</th>
 <th scope="col">Next Execution</th>
 </tr>
 </thead>
 <tbody class= "scheduledBody">
 <script id="scheduled-task" type="text/x-handlebars-template">
 {{#each schedules}}
 <tr>
 <th>{{name}}</th>
 <td>{{type}}</td>
 <td data-countdown="{{timeSs}}"></td>
 </tr>
 {{/each}}
 </script>
 </tbody>
</table>

关键说明

  • 完全无外部依赖:所有代码都是原生JS和jQuery(你已经在使用jQuery做AJAX),不需要额外引入库。
  • 时间处理完善:自动处理目标时间已过的情况,显示“已执行”。
  • 美观的格式化:时分秒自动补零,保证显示格式统一。
  • 即时显示:初始化时立即渲染倒计时,避免用户等待1秒才看到内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:31:42