我需要创建一个计数器,将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 );
答案 0 :(得分:2)
counter.js
脚本正在加载到文档head
上,即在创建#counter
元素之前。这意味着这段代码:
var clickNumber = document.getElementById("counter");
将导致clickNumber
为null
(因为该元素尚不存在)。
您可以通过在加载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 );