如何在同一html页面中添加多个倒计时计时器查询

How To add multiple Countdown timer query in a same html page?

本文关键字:添加 倒计时 查询 计时器 html      更新时间:2023-09-26

我想创建一个在线拍卖网站。我需要提及每个拍卖结束时间& &;日期。

我创建了一个countdown.js文件,如下所示:
// set the date we're counting down to
var target_date = new Date("Aug 15, 2014").getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
// update the tag with id "countdown" every 1 second
setInterval(function () {
    // find the amount of "seconds" between now and target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;
    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;
    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;
    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);
    // format countdown string + set tag value
    countdown.innerHTML = days + " D : " + hours + " H : " + minutes + " M : " + seconds + " S";
}, 1000);

我在我的html中导入了如下内容:

<script type="text/javascript"src="js/countdown.js"></script>
 <p style="font-size:larger;color:Red;font-weight:bolder">END IN</p>
                    <h5><i id="countdown"></i></h5><br />

工作得很好。现在我想在同一页面中添加一个或多个计时器。当我使用以下代码

<h5><i id="countdown"></i></h5><br />

显示ID错误。如何纠正这种情况?

只需将代码移动到一个函数中,该函数接受两个参数元素id和目标日期

  function setTimer(elem_id, date) {
 // set the date we're counting down to
var target_date = new Date(date).getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countDownElem = document.getElementById(elem_id);
//update the tag with id "countdown" every 1 second
setInterval(function () {
   // find the amount of "seconds" between now and target
  var current_date = new Date().getTime();
  var seconds_left = (target_date - current_date) / 1000;
  // do some time calculations
  days = parseInt(seconds_left / 86400);
  seconds_left = seconds_left % 86400;
  hours = parseInt(seconds_left / 3600);
  seconds_left = seconds_left % 3600;
  minutes = parseInt(seconds_left / 60);
  seconds = parseInt(seconds_left % 60);
  // format countdown string + set tag value
  countDownElem.innerHTML = days + " D : " + hours + " H : " + minutes + " M : " + seconds + " S";
}, 1000);
}
setTimer("countdown1","Aug 15, 2014");
setTimer("countdown2","Aug 17, 2014");

上面的代码

上面的答案有效,但我注意到第二个计时器显示比第一个计时器长一个小时。