首页 > 解决方案 > 我用于将项目附加到 ul 的代码不起作用 javascript

问题描述

我已将此 js 代码放入 Visual Studio,但它不会工作。请帮忙:

var task = document.getElementById('action');
var button = document.getElementById('button');
var err = document.getElementById('err');
var list = document.getElementById('tasks');

button.addEventListener("click", function() {
  if (task.value == "") {
    err.style.backgroundColor = 'red';
    err.innerHTML = "Please enter a value";
  } else {
    var newItem = document.createElement("li");
    newItem.innerHTML = task.nodeValue;
    list.appendChild(newItem);
    err.style.backgroundColor = "none";
    err.innerHTML = "";
    task.nodeValue = "";
  }
})
<header id="header" style="background-color:green;">
  <div id="title">To-Do</div>
  <div id="date"></div>
</header>
<br>
<hr>
<div id="mains">
  <p id="err"></p>
  <label for="text">Task: </label>
  <input type="text" id="action" name="text" placeholder="Wash the dishes..."><br>
  <button id=button>Add</button>
  <ul id="tasks"></ul>
</div>

当我按“添加”时,没有任何反应,文本保持不变,ul 不变

标签: javascripthtml

解决方案


I guess, the problem in this line:

 newItem.innerHTML = task.nodeValue;

It will work if you'll replace task.nodeValue with task.value;

According to the documentation your task.nodeValue will be always null. And moreover, in your code the "if" statement checks task.value


推荐阅读