addEventListener 方法无法正常工作
2020-08-05
71
我正在构建简单的计数器应用程序,但在 Javascript 中
addEventListern
无法运行,并出现以下错误:
这是我尝试过的 JavaScript 代码,但仍然出现错误
Cannot read property 'addEventLister' of Null
//selecting elements
let value = document.getElementById('value');
let counter = 0;
value.textContent = counter;
// addingEventListener
document.getElementById('reset').addEventListener('click', reset);
document.getElementById('increase').addEventListener('click', increase);
document.getElementById('decrease').addEventListener('click', decrease);
// Event functions
function reset() {
counter = 0;
}
function increase() {
counter++;
}
function decrease() {
counter--;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="main">
<div class="container">
<p class="two-times">Counter</p>
<p class="two-times" id="value">0</p>
<div class="buttons">
<input class="btn" id="decrease" type="button" value="Recrease">
<input class="btn" id="reset" type="button" value="Reset">
<input class="btn" id="Increase" type="button" value="Increase">
</div>
</div>
</div>
<!-- javaScript -->
<script src="app.js"></script>
</body>
</html>
2个回答
document.getElementById('increase').addEventListener('click', increase);
且
<input class="btn" id="Increase" type="button" value="Increase">
不匹配
//selecting elements
let value = document.getElementById('value');
let counter = 0;
value.textContent = counter;
// addingEventListener
document.getElementById('reset').addEventListener('click', reset);
document.getElementById('Increase').addEventListener('click', increase);
document.getElementById('decrease').addEventListener('click', decrease);
// Event functions
function reset() {
counter = 0;
}
function increase() {
counter++;
}
function decrease() {
counter--;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="main">
<div class="container">
<p class="two-times">Counter</p>
<p class="two-times" id="value">0</p>
<div class="buttons">
<input class="btn" id="decrease" type="button" value="Recrease">
<input class="btn" id="reset" type="button" value="Reset">
<input class="btn" id="Increase" type="button" value="Increase">
</div>
</div>
</div>
<!-- javaScript -->
<script src="app.js"></script>
</body>
</html>
fedesc
2020-08-05
您输入错误。输入元素的 ID 为大写(Increase),而您尝试使用小写名称(increase)访问它。
stefxq
2020-08-05