如何从HTML元素中获取数字值,我将在倒计时中使用它?我不断收到错误,document.getElementById(...)为null,我错过了连接的东西?这里的小提琴:https://jsfiddle.net/L6ddLc0L/使用JavaScript从HTML元素获取数值
<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);
}
'parseInt函数()'是一个函数,而不是一个方法,即需要'parseInt函数(STR)','未str.parseInt()'。另外,当你通过属性(onclick)等使用内联,DOM零事件时,你的Fiddle会失败。由于JS Fiddle代码被封闭,所以它们不会找到它们调用的函数。改为使用适当的事件注册。 – Utkanos
您问题中的代码未能显示您如何加载JS。没有脚本标签。 JS Fiddle中的代码给出了你在问题中描述的完全不同的错误信息。你需要提供一个**真实的** [MCVE],然后才能确定你的*真实*问题。 – Quentin
'document.getElementById()'找不到元素的典型原因是,在HTML(和有问题的元素)的其余部分加载完成之前,一旦加载了'
',就会运行JavaScript代码。当然,你共享的代码不会出现这个问题。 –