我非常感谢您的帮助。 document.querySelector 不选择元素并抛出 ReferenceError: document is not defined - 在 vscode 控制台上,和 Uncaught ReferenceError: input is not defined in the devtools console (that's同样的问题导致“document.querySelector”没有选择任何东西。) 我的脚本标签在 body 标签的末尾。 什么可能导致错误?
const inputBox = document.querySelector('.inputField input');
const addBtn = document.querySelector('.inputField button');
inputBox.onkeyup = () => {
let userData = inputBox.value;
if (userData.trim() !== 0) {
addBtn.classList.add("active");
} else {
addBtn.classList.remove("active");
}
}
//if user click on the add button
addBtn.onclick = () => {
let userData = inputBox.value;
let getLocalStorage = localStorage.getItem("New Todo");
if (getLocalStorage == null) {
listArr = [];
} else {
listArr = JSON.parse(getLocalStorage);
}
listArr.push(userData);
localStorage.setItem("New Todo", JSON.stringify(listArr));
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>to-do-list</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
</head>
<body>
<div class="wrapper">
<header>Todo App</header>
<div class="inputField">
<input type="text" placeholder="Add here...">
<button><span class="lnr lnr-plus-circle"></span></button>
</div>
<ul class="todolist">
<li>Buy something new<span class="lnr lnr-trash"></span></li>
<li>Buy something 2<span class="lnr lnr-trash"></span></li>
<li>Buy something 3<span class="lnr lnr-trash"></span></li>
<li>Buy something 4<span class="lnr lnr-trash"></span></li>
</ul>
<div class="footer">
<span>You have 4 pending tasks</span>
<button>Clear All</button>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
答案 0 :(得分:-1)
您正在尝试访问 input
而不是 inputBox
。同样,根本没有定义 listArr
。
addBtn.onclick = () => {
let userData = inputBox.value;
let getLocalStorage = localStorage.getItem("Todos");
let listArr = getLocalStorage !== null ? JSON.parse(getLocalStorage) : [];
listArr.push(userData);
localStorage.setItem("Todos", JSON.stringify(listArr));
}