javascript - 通过 Date() 显示时间 : it is not being updated using setInterval()

标签 javascript jquery

我有这个代码来用西类牙语显示时间和一些日期信息:

  var date = new Date();

  var hour = date.getHours().toString();
  var minutes = date.getMinutes().toString();

  var day = date.getDate();

  switch (date.getMonth()) {
      case 0:
      month = "Ene";
      break;
      case 1:
      month = "Feb";
      break;
      case 2:
      month = "Mar";
      break;
      case 3:
      month = "Abr";
      break;
      case 4:
      month = "May";
      break;
      case 5:
      month = "Jun";
      break;
      case 6:
      month = "Jul";
      break;
      case 7:
      month = "Ago";
      break;
      case 8:
      month = "Sep";
      break;
      case 9:
      month = "Oct";
      break;
      case 10:
      month = "Nov";
      break;
      case 11:
      month = "Dic";
      break;
  } 

  if (hour.length == 1) { 
    hour = '0' + hour;
  }
  if (minutes.length == 1) { 
    minutes = '0' + minutes;
  }
  setInterval($('#hour').html('<b>' + hour + ':' + minutes + '<br>' + '<span class="day">' + day + ' ' + month + '</span></b>'), 60000);

当我加载文档时,它工作正常。问题是时间永远不会更新..为什么?

最佳答案

正如@Travis J 所指出的,setTimeout 第一个参数应该是一个函数。 (参见the doc。)

在您的情况下,您还希望此函数在每次调用时重新计算日期。

所以类似:

// Define a function that will update the html from current date
function updateDate() {
  var date = new Date();

  var hour = date.getHours().toString();
  var minutes = date.getMinutes().toString();

  var day = date.getDate();

  switch (date.getMonth()) {
      case 0:
      month = "Ene";
      break;
  ...
  }

  if (hour.length == 1) { 
    hour = '0' + hour;
  }
  if (minutes.length == 1) { 
    minutes = '0' + minutes;
  }

  // Update the page content
  $('#hour').html('<b>' + hour + ':' + minutes + '<br>' + '<span class="day">' + day + ' ' + month + '</span></b>' 
}

// Call the function the first time (setInterval will not call it right away)
updateDate();

// Schedule the function to be called every minute after that
setInterval(updateDate, 60000);

关于javascript - 通过 Date() 显示时间 : it is not being updated using setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927009/

相关文章:

javascript - 使用 lodash 将一个字符串转换为另一个字符串

javascript - 如果 wrapper 元素是 -4000 px left alert

javascript - 页面上的多个表单,Ajax 在错误的表单上显示错误

javascript - react 路由器中的浏览器历史记录

JavaScript 正则表达式 (?i)^inf

javascript - 带有进度条的图像交换增加/减少onclick

如果我在其中使用警报,Javascript 代码就可以工作,否则它就无法工作

javascript - 如何使 jQuery 可排序放在空列上?

javascript - jQuery中通过data属性和部分id获取元素

Javascript 打印在 IE9 中不工作