如何从HTML元素中获取数字值,我稍后会在倒计时中使用?我一直收到document.getElementById(...)为null的错误,我错过了连接的东西吗?这是小提琴:https://jsfiddle.net/L6ddLc0L/
<h1 id="num">50</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>Increase</button>
var num = document.getElementById('num').innerHTML;
var secs = num.parseInt();
function increaseNumber() {
secs++;
}
function countDown(secs, elem) {
var element = document.getElementById(elem); //(elem)
element.innerHTML = "Please wait for "+secs+" seconds";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += '<a href="#">Click here now</a>';
}
secs--;
var timer = setTimeout('countDown('+secs+', "'+elem+'")',1000);
}
答案 0 :(得分:2)
答案 1 :(得分:1)
我将https
- 方法更改为实际的parseInt
并修复了错误的function
参数。正如其他人所提到的,你应该注意到Javascript会在浏览器解释时被执行。因此,如果您在setTimeout
中添加<script>
标记,该标记将访问正文字段,则无法找到它们,因为它们尚未被浏览器解释。
<head>
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function increaseNumber() {
secs++;
}
function countDown(secs, elem) {
var element = document.getElementById(elem); //(elem)
element.innerHTML = "Please wait for " + secs + " seconds";
//if timer goes into negative numbers
if (secs < 1) {
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += '<a href="#">Click here now</a>';
}
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
}