首页 > 解决方案 > 当我尝试为我的待办事项列表应用程序创建 LI 元素时,我的浏览器屏幕上没有显示任何内容

问题描述

我一直在用 JavaScript 开发这个待办事项列表应用程序,并尝试了几种不同的方法,但我无法让我的列表显示在屏幕上。我尝试初始化一个空数组并将 input.value 推送到我的函数和 console.logging 数组中的数组中,这有效但只显示我输入的当前值,而不是保存所有值。所以我的问题是,为什么我的函数不向屏幕添加列表元素,以及第 2 部分,如果我要使用空数组,如何获取显示的数组中的每个元素。我是 JavaScript 的初学者,看过很多关于用户输入和document.getElementByIdStack 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>

标签: javascriptarrayslistuser-input

解决方案


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>


推荐阅读