3个Javascript计数器在同一页面上

时间:2018-06-05 17:23:47

标签: javascript

您好。我有一个问题。

我刚为我的媒体课程制作了一个考试网页。 这是挪威政府部门称为“Helsedirektoratet”的态度运动

所以问题是它不会同时向我显示所有三个计数器。 所以,如果有人能帮助我那将是伟大的!

(第一次使用Javascript)

<div id="seconds-counter"> </div>
<script>
  var seconds = 0;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
    seconds += 1;
    el.innerText = "Du har vært sukkerfri " + seconds + " sekunder.";
  }

  var cancel = setInterval(incrementSeconds, 1000);
</script>
<div id="seconds-counter"> </div>
<script>
  var seconds = 3;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
    seconds += 2;
    el.innerText = "Du har også spart " + seconds + " kroner.";
  }
  var cancel = setInterval(incrementSeconds, 1000);
</script>
<div id="seconds-counter"> </div>
<script>
  var seconds = 1;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
    seconds += 0.5;
    el.innerText = "Du har også spart " + seconds + " kalorier.";
  }
  var cancel = setInterval(incrementSeconds, 1000);
</script>

2 个答案:

答案 0 :(得分:0)

您需要更改de DIV ID,例如:

<div id="seconds-counter"> </div>
<script>
  var seconds = 0;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
    seconds += 1;
    el.innerText = "Du har vært sukkerfri " + seconds + " sekunder.";
  }

  var cancel = setInterval(incrementSeconds, 1000);
</script>
<div id="seconds-counter-kroner"> </div>
<script>
  var seconds = 3;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
    seconds += 2;
    el.innerText = "Du har også spart " + seconds + " kroner.";
  }
  var cancel = setInterval(incrementSeconds, 1000);
</script>
<div id="seconds-counter-kalorier"> </div>
<script>
  var seconds = 1;
  var el = document.getElementById('seconds-counter');

  function incrementSeconds() {
    seconds += 0.5;
    el.innerText = "Du har også spart " + seconds + " kalorier.";
  }
  var cancel = setInterval(incrementSeconds, 1000);
</script>

这样做可以避免覆盖。

答案 1 :(得分:0)

您可能希望将代码包装到函数中以创建计时器。通过这种方式,您可以缩短代码,并且可以封装变量,以便为所有不同的计时器获得不同的值:

function createTimer(message, selector) {
  var seconds = 0;
  var el = document.getElementById(selector);

  function incrementSeconds() {
     seconds += 1;
     el.innerText = message + seconds + " sekunder.";
   }

   setInterval(incrementSeconds, 1000);
}

所以你可以这样做:

createTimer("Du har vært sukkerfri ", "seconds-counter");
createTimer("Something else ", "seconds-counter2");

PS:DOM中的ID应该是唯一的。