[英]Uncaught TypeError: Cannot set property 'textContent' of null at HTMLButtonElement.<anonymous> (index.js:17), why is it happening?
I was doing a counter project and had this issue a couple of times but I couldn't find what the issue was so I copy and pasted the js from a counter project that free code camp did and that won't work.我正在做一个计数器项目并且遇到过几次这个问题,但我找不到问题所在,所以我从免费代码营所做的计数器项目中复制并粘贴了 js,但这不起作用。 What am I missing?
我错过了什么? Also, any best practice tips and general advice is appreciated.
此外,感谢任何最佳实践技巧和一般建议。
HTML 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 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;
});
});
As noted in comments, mistake is here const value = document.querySelector("counter");
如评论中所述,错误在这里
const value = document.querySelector("counter");
This selector selects non-existent HTML element counter
.此选择器选择不存在的 HTML 元素
counter
。 Should select by class or id, like const value = document.querySelector(".counter");
select 应该是 class 还是 id,比如
const value = document.querySelector(".counter");
or const value = document.querySelector("#counter");
或
const value = document.querySelector("#counter");
. . Both valid for this example, but for unique element id is preferred.
两者都适用于本示例,但首选唯一元素 id。
Regarding general advice, this code is out of sync since start - shows 54, but the real value of counter is 0. Avoid that.关于一般建议,此代码自启动以来不同步 - 显示 54,但计数器的实际值为 0。避免这种情况。 You can set initial text in counter element from the actual value or vice versa - set counter value from the text value on page init.
您可以根据实际值在计数器元素中设置初始文本,反之亦然 - 从页面 init 上的文本值设置计数器值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.