var today = new Date();
var day = today.getDay()
var month = today.getMonth();
var year = today.getFullYear()
var date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;

function dateTimeClock() {
  $('#today').text(today);
  $('#day').text(day);
  $('#month').text(month);
  $('#year').text(year);
  $('#date').text(date);
  $('#time').text(time);
  $('#dateTime').text(dateTime);
}

setInterval(dateTimeClock, 1000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<p id="today"></p>
<p id="day"></p>
<p id="month"></p>
<p id="year"></p>
<p id="date"></p>
<p id="time"></p>
<p id="dateTime"></p>





有人可以告诉我为什么setInterval没有启动吗?

我希望我的数据每秒刷新一次。

最佳答案

date的var在时间间隔之外定义,因此不会更新。要解决此问题,您必须将其包括在dateTimeClock函数中


function dateTimeClock() {

var today = new Date();
var day = today.getDay()
var month = today.getMonth();
var year = today.getFullYear()
var date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;
  $('#today').text(today);
  $('#day').text(day);
  $('#month').text(month);
  $('#year').text(year);
  $('#date').text(date);
  $('#time').text(time);
  $('#dateTime').text(dateTime);
}

setInterval(dateTimeClock, 1000);

关于javascript - setInterval不是每秒刷新一次数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60343134/

10-13 04:34