javascript
2016-09-22 46 views -2 likes 
-2

如何从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); 
} 
+2

'parseInt函数()'是一个函数,而不是一个方法,即需要'parseInt函数(STR)','未str.parseInt()'。另外,当你通过属性(onclick)等使用内联,DOM零事件时,你的Fiddle会失败。由于JS Fiddle代码被封闭,所以它们不会找到它们调用的函数。改为使用适当的事件注册。 – Utkanos

+2

您问题中的代码未能显示您如何加载JS。没有脚本标签。 JS Fiddle中的代码给出了你在问题中描述的完全不同的错误信息。你需要提供一个**真实的** [MCVE],然后才能确定你的*真实*问题。 – Quentin

+1

'document.getElementById()'找不到元素的典型原因是,在HTML(和有问题的元素)的其余部分加载完成之前,一旦加载了'',就会运行JavaScript代码。当然,你共享的代码不会出现这个问题。 –

回答

1

我改变了parseInt - 方法为function,它实际上是固定的坏setTimeout参数。正如其他人提到的那样,你应该注意到Javascript在被浏览器解释时会被执行。因此,如果您在您的<head>中加入<script> -tag标签,该标签将访问身体的字段,但由于它们尚未被浏览器解释,因此它们将无法找到它们。

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); 
 
}
<h1 id="num">50</h1> 
 

 
<div id="status"></div> 
 

 
<button onclick='countDown(secs, "status")'>Start countdown</button> 
 
<button onclick='increaseNumber()'>Increase</button>

+0

'var num = document.getElementById('num')。innerHTML;'必须在元素渲染后执行 – mplungjan

2

你不好使用parseInt函数()。你必须这样称呼它。

var secs = parseInt(num,10); 

也看看here你如何在HTML代码应该看起来

+1

正确。但他说* document.getElementById(...)是null *,所以他之前有一些其他问题。 –

相关问题