javascript - 我用于将项目附加到 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 不变
解决方案
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
推荐阅读
- python - 如何从 url 端点获取 POST 结果?Django/Python
- javascript - 如何为 Chart.js 中的每个区域应用不同的背景颜色
- amazon-web-services - AWS 工作区 vpn
- python - Python如何在引号中设置变量
- javascript - 当我尝试将 websocket 连接到我的服务器时出现此错误
- .net - Devops 和 Bitbucket 构建管道 - 磁盘空间不足
- flutter - Flutter Web - 如何在 ListView 中隐藏滚动条?
- amazon-web-services - 是否可以使用 AWS 转录将人员映射到转录本?
- c# - 如何将此逻辑从 LabVIEW 转换为 C# - 十六进制字符串到字节数组并将字节数组类型转换为单个
- javascript - Nodejs:TypeError:require()。()不是一个函数