为什么我会收到“无法读取值为空的属性”错误?
2019-09-13
738
我正在尝试创建一个基本的待办事项列表应用,目前尝试将 taskInput.value 文本节点附加到 li。但是,在控制台中测试时,我收到错误“Uncaught TypeError:无法读取 null 的属性‘value’”。这是为什么?
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div class="container">
<form id="form-input">
<div class="form-group">
<label class="h2 mb-2" for="Enter Task">Enter Task</label>
<input type="text" class="form-control" id="#taskInput" name="taskInput" placeholder="Enter your task...">
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="task-list">
<h3 class="mt-3">Task List</h3>
<ul class="list-group">
</ul>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/732aafddc7.js"></script>
<script src="app.js"></script>
</body>
</html>
const form = document.querySelector('#form-input');
const taskInput = document.querySelector('#taskInput');
const taskList = document.querySelector('ul.list-group');
form.addEventListener('submit', addTask);
function addTask(e) {
// create element
const li = document.createElement('li');
// add class
li.className = 'list-group-item d-flex justify-content-between';
// create text node and append
li.appendChild(document.createTextNode(taskInput.value));
console.log(li);
e.preventDefault();
}
1个回答
li.appendChild(document.createTextNode(taskInput.value));
不正确。您应该先创建一个元素,然后获取其值:
li.appendChild(document.createTextNode(taskInput));
const value = document.getElementById('taskInput').value;
编辑:另外,查看您的 html,您需要将
id="#taskInput"
更改为
id="taskInput"
,然后在您的 JS 中,您可以按如下方式获取它:
const taskInput = document.getElementById('taskInput');
Clarity
2019-09-13