![](/img/trans.png)
[英]Uncaught TypeError: Cannot read properties of null (reading 'push') at HTMLButtonElement.<anonymous> (main.js:15:23)
[英]Uncaught TypeError: Cannot set property 'textContent' of null at HTMLButtonElement.<anonymous> (index.js:17), why is it happening?
我正在做一個計數器項目並且遇到過幾次這個問題,但我找不到問題所在,所以我從免費代碼營所做的計數器項目中復制並粘貼了 js,但這不起作用。 我錯過了什么? 此外,感謝任何最佳實踐技巧和一般建議。
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="index.css">
<title>Counter</title>
</head>
<body>
<div class="container">
<div class="counterContainer">
<h1>Counter</h1>
<br>
<div class="counter" id="counter">
54
</div>
</div>
<div class="buttonContainer">
<button type="button" class="decreaseButton button" id="decreaseButton">
Decrease
</button>
<button type="button" class="resetButton button" id="resetButton">
Reset
</button>
<button type="button" class="increaseButton button" id="increaseButton">
increase
</button>
</div>
</div>
<script src="index.js">
</script>
</body>
</html>
js
// set inital value to zero
let count = 0;
// select value and buttons
const value = document.querySelector("counter");
const btns = document.querySelectorAll("button");
btns.forEach(function (btn) {
btn.addEventListener("click", function (e) {
const styles = e.currentTarget.classList;
if (styles.contains("decreaseButton")) {
count--;
} else if (styles.contains("increaseButton")) {
count++;
} else {
count = 0;
}
value.textContent = count;
});
});
如評論中所述,錯誤在這里const value = document.querySelector("counter");
此選擇器選擇不存在的 HTML 元素counter
。 select 應該是 class 還是 id,比如const value = document.querySelector(".counter");
或const value = document.querySelector("#counter");
. 兩者都適用於本示例,但首選唯一元素 id。
關於一般建議,此代碼自啟動以來不同步 - 顯示 54,但計數器的實際值為 0。避免這種情況。 您可以根據實際值在計數器元素中設置初始文本,反之亦然 - 從頁面 init 上的文本值設置計數器值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.