使用JavaScript从HTML元素中获取数字值

时间:2016-09-22 10:21:25

标签: javascript

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

2 个答案:

答案 0 :(得分:2)

你很难使用parseInt()。你必须这样称呼它。

var secs = parseInt(num,10);

另请查看here html中的代码应如何显示

答案 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);
}