为什么这个简单的JavaScript秒表不起作用?

时间:2016-11-06 20:32:44

标签: javascript chronometer

我写了一些非常简单的代码,应该代表一个带有两个按钮的秒表,点击“开始”应该从0开始向上计数,延迟时间为1秒。

然而,当我点击没有任何变化。我的错误在哪里?

"use strict";
var s = 1;

function mf() {
  setInterval(function() {
    document.getElementById("#sw").innerText = ++s;
  }, 1000);
}
<div id="sw">0</div>
<input type="button" value="Start" name="start" onlick="mf" />
<input type="button" value="Stop" name="stop" />

2 个答案:

答案 0 :(得分:4)

您有两个问题:

1):您正在使用

onlick="mf"

但是,它应该是:

onclick="mf();"

2):您在&#39; getElementByID&#39;中使用了#。这不是jQuery-使用

document.getElementById("sw")

工作答案

&#13;
&#13;
"use strict";
 var s = 1;

  function mf() {
  setInterval(function() {
    document.getElementById("sw").innerText = s++;
   }, 1000);
 }
&#13;
<div id="sw">0</div>
<input type="button" value="Start" name="start" onclick="mf();" />
<input type="button" value="Stop" name="stop" />
&#13;
&#13;
&#13;

您的错误:

    document.getElementById("#sw").innerText = ++s;

应该是

    document.getElementById("sw").innerText = s++;

删除#,然后使用s++,而不是++s

 <input type="button" value="Start" name="start" onlick="mf" />

该代码有2个错误:onlickmf。所有浏览器(xD)都不支持Onlick。请改用onclick。另外,请包含参数,因此mf()

答案 1 :(得分:1)

首先,你有一个错字。您输入了onlick而不是onclick。其次,document.getElementById接受一个字符串,该字符串引用您要获取的元素的id。但是,它不需要#。

document.getElementById("sw")
相关问题