为什么我的clickNumber变量没有保留选定的dom元素?

时间:2017-11-19 21:20:18

标签: javascript

我需要创建一个计数器,将click事件处理程序附加到增量按钮。必须有2个函数,并且必须在函数外声明变量。为什么它无法读取clickNumber的值?如果我在增量函数中声明了它的作用。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Counter</title>
    <script src="counter.js"></script>
</head>
<body>

<div>
    <button id="increment">Increment</button>
    <p id="counter">Counter = 0</p>


</div>


</body>
</html>

JS

var counter = 0;
var clickNumber = document.getElementById("counter");



function getElementBtnIncrement() {

    document.getElementById("increment").addEventListener("click",increment,false);

}


function increment(){
    counter++;
    clickNumber.innerHTML = "Count = " + counter;
}



window.addEventListener( "load", getElementBtnIncrement, false );

1 个答案:

答案 0 :(得分:2)

counter.js脚本正在加载到文档head上,即在创建#counter元素之前。这意味着这段代码:

var clickNumber = document.getElementById("counter");

将导致clickNumbernull(因为该元素尚不存在)。

您可以通过在加载DOM后分配clickNumber值来解决此问题:

var counter = 0;
var clickNumber; // still declared outside, but the value is assigned later



function getElementBtnIncrement() {

    document.getElementById("increment").addEventListener("click",increment,false);

}


function increment(){
    counter++;
    clickNumber.innerHTML = "Count = " + counter;
}



window.addEventListener( "load", function() {
  clickNumber = document.getElementById("counter");
  getElementBtnIncrement();
}, false );