javascript - 当我尝试为我的待办事项列表应用程序创建 LI 元素时,我的浏览器屏幕上没有显示任何内容
问题描述
我一直在用 JavaScript 开发这个待办事项列表应用程序,并尝试了几种不同的方法,但我无法让我的列表显示在屏幕上。我尝试初始化一个空数组并将 input.value 推送到我的函数和 console.logging 数组中的数组中,这有效但只显示我输入的当前值,而不是保存所有值。所以我的问题是,为什么我的函数不向屏幕添加列表元素,以及第 2 部分,如果我要使用空数组,如何获取显示的数组中的每个元素。我是 JavaScript 的初学者,看过很多关于用户输入和document.getElementById
Stack Overflow 的页面,但我希望有人能帮助解释为什么我的代码没有运行。
我的 HTML:
//This is my code for trying to add li and get it to display on screen:
//when I run this in the browser, there are no errors, but also nothing happens.
function newTodo() {
var input = document.getElementById("todo-text").value;
const list = document.getElementById("todo-list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("- " + input));
list.appendChild(li);
document.getElementById("input").value = "";
}
document.body.onkeyup = function(e) {
if (e.keyCode === 13) {
newTodo();
}
};
// Editor Note: Commenting this code out since it defines the same function name
/*
//Option 2 I have tried:
//JavaScript array todo:
window.onload = function() {
const button = document.getElementById('btn');
button.addEventListener("click", newTodo, false);
}
let todoItems = [];
//prints element on console when typed, but when I try to add a new element the page refreshes with a new array instead of adding to same array
function newTodo() {
input = document.getElementById('todo-text');
todoItems.push(input.value);
input.value = "";
console.log(todoItems);
}
*/
<form class="add-todo">
<input type="text" id="todo-text" name="newTodo">
<button class="button center" id="btn">New TODO</button>
</form>
<ul id="todo-list" class="todo-list"></ul>
解决方案
function newTodo(evt) {
evt.preventDefault();
const input = document.getElementById("todo-text").value;
const list = document.getElementById("todo-list");
const li = document.createElement("li");
li.appendChild(document.createTextNode("- " + input));
list.appendChild(li);
document.getElementById("todo-text").value = "";
}
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("my-form").addEventListener("submit", newTodo, false);
});
<html>
<head></head>
<body>
<form class="add-todo" id="my-form">
<input type="text" id="todo-text" name="newTodo">
</form>
<ul id="todo-list" class="todo-list"></ul>
</body>
</html>
推荐阅读
- android - 如何限制 Places Autocomplete api 仅返回距当前位置 2 公里范围内的地点
- macos - 设置 CS50 IDE 时遇到问题
- python - 访问 with-block 之外的值
- reactjs - 如何使用 React 将数据插入到影子 dom 中?
- javascript - 如何在 IE 以外的浏览器中使用 Angular 中的输入类型 = 文件获取完整文件路径
- python - 如何使用 Python NLP 从句子列表中提取特定单词。这些词是医疗设备的零件
- python - 在 Pandas Dataframe 中出现语法错误
- flutter - 获取其他位置的天气,即使经过正确的纬度和经度
- sqlite - 如何重置 Superset 的数据库?
- mysql - 为什么这个 Laravel 雄辩的查询会返回更多的对象?