gpt4 book ai didi

javascript - 变量将 DOM 元素处理为 null。为什么会发生这种情况?

转载 作者:行者123 更新时间:2023-12-01 00:55:05 25 4
gpt4 key购买 nike

在此代码中,我尝试将 DOM 元素分配给变量,但变量的值为 null。为什么会发生这种情况?我是不是犯了什么错误?

<!DOCTYPE html>
<html>
<head>
<title>Tasks</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A simple task list for your day-to-day.">
<meta name="author" content="Bruno M. B. Sdoukos">
<meta name="keywords" content="task list, checklist">
<script>
var taskCreator = document.querySelector('#taskcreator');
var list = document.querySelector('ul');
var taskInput = document.querySelector('#taskinput');
</script>
</head>
<body>
<ul></ul>
<input type="text" id="taskinput">
<button id="taskcreator">Create new item</button>
</body>
</html>

最佳答案

当浏览器执行你的javascrit时,还没有输入和按钮。您可以使用

修复它
<!DOCTYPE html>
<html>
<head>
<title>Tasks</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A simple task list for your day-to-day.">
<meta name="author" content="Bruno M. B. Sdoukos">
<meta name="keywords" content="task list, checklist">
</head>
<body>
<ul></ul>
<input type="text" id="taskinput">
<button id="taskcreator">Create new item</button>
<script>
var taskCreator = document.querySelector('#taskcreator');
var list = document.querySelector('ul');
var taskInput = document.querySelector('#taskinput');
taskCreator.addEventListener('click', function createNewTask(event) {
list.innerHTML += '<li>' + taskInput.value + '</li>'
})
</script>
</body>
</html>

或者在脚本中等待,直到整个文件被解析。

<script>
document.addEventListener("DOMContentLoaded", function () {
var taskCreator = document.querySelector('#taskcreator');
var list = document.querySelector('ul');
var taskInput = document.querySelector('#taskinput');
taskCreator.addEventListener('click', function createNewTask(event) {
list.innerHTML += '<li>' + taskInput.value + '</li>'
})
});
</script>

https://developer.mozilla.org/ru/docs/Web/Events/DOMContentLoaded

关于javascript - 变量将 DOM 元素处理为 null。为什么会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56649635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com