【发布时间】:2022-01-20 17:19:20
【问题描述】:
切换开关时,我从浏览器控制台收到这些错误。出于某种原因,它不起作用,我无法解决为什么它不起作用我刚刚开始使用 Javascript,所以如果我做了一些愚蠢的事情,请不要生我的气。
Uncaught TypeError: Cannot read properties of undefined (reading 'remove')
at getValue (darkModeSwitch.js:8)
at window.onload (index.html:17)
Uncaught TypeError: Cannot read properties of undefined (reading 'add')
at getValue (darkModeSwitch.js:13)
at HTMLInputElement.onclick (index.html:26)
HTML:
<div>
<ul>
<li><a href="kapcsolat/kapcsolat.html?version=691">Kapcsolat</a></li>
<li><a href="projects/projects.html?version=691">Projektek</li>
<li><a class="active" href="index.html?version=692">Kezdőlap</a></li>
<li><label class="switch"><input onclick="getValue()" id="darkModeToggle" type="checkbox" checked><span class="slider round"></span></label><script src="scripts/darkModeSwitch.js"></script>
</li>
<h1 class="jayden" style="float: left;"><a class="jayden" href="index.html?version=-23424893215">jayden.hu</a></h1>
</ul>
</div>
CSS:
.lightmode{
background-color: white;
color: black;
}
Javascript:
const body = document.body
const anchor = document.getElementsByTagName("a");
const darkModeToggle = document.getElementById('darkModeToggle');
function getValue(){
if (darkModeToggle.checked) {
body.classList.remove("lightmode")
anchor.classList.remove("lightmode")
console.log("checked")
} else{
console.log("not checked")
body.classList.add("lightmode")
anchor.classList.add("lightmode")
}
};
【问题讨论】:
-
是 JS 代码
const body = document.body等 - 在页面加载后执行吗?尝试将变量初始化包装在window.addEventListener('DOMContentLoaded', () => { -
我有这样的。
-
document.getElementsByTagName返回元素的数组[],这就是为什么anchor.classList是 undefined 。您应该专门找到要切换类的元素。
标签: javascript html css web