为什么会出现“无法读取null值的属性”错误?

时间:2019-09-13 07:25:54

标签: javascript dom

我正在尝试创建一个基本的待办事项列表应用程序,当前正在尝试将taskInput.value文本节点附加到li上。但是,在控制台中对其进行测试时,出现错误“未捕获的TypeError:无法读取null的属性”值”。为什么会这样?

<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 个答案:

答案 0 :(得分: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');