【发布时间】:2019-03-04 21:23:13
【问题描述】:
成品应该在每个条目旁边都有一个复选框,以及编辑或删除每个项目的选项。我还差得很远,因为我什至无法发布要发布的项目。
另外,我很抱歉格式化。我没有粘贴 CSS,因为就我而言这不是问题。
HTML:
var list = document.getElementById('list'); //The unordered list.
var entry = document.createElement("li"); //Whatever this is. I'm assuming a command saved into a variable (?).
//var todolist = list.getElementsById('li');
// var btn = document.getElementById('ToDoButton');
//
// btn.addEventListener("click", function(){
// todolist.appendChild('li');
// });
/* Upon submission of the item in the text field, the string is stored in inputValue
and theText becomes a text node of inputValue, which is appended to the end of the variable
entry. This means that there should be a new item added to the unordered list with the information
found in the text field, but it doesn't show.
Also, as far as I know, this is only if the Add button is clicked, and not upon
pressing Enter while in the text box. */
function newElement() {
var inputValue = document.getElementById("textBox").value;
var theText = document.createTextNode(inputValue);
entry.appendChild(theText);
if (inputValue !== '') {
document.getElementById(list).appendChild(entry);
}
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" href="todo.css">
</head>
<body>
<div class="toDoList">
<h4>To-Do List</h4>
<form target="_self">
<!-- This is so that the submitted information doesn't go anywhere but to the current page. -->
<input type="text" name="toDoList" placeholder="To-Do" id="textBox">
<input type="submit" value="Add" onclick="newElement()" id="ToDoButton">
<!-- newElement() is a JS function that will add the information in the search bar to the unordered list below. -->
</form>
</div>
<section id="main">
Tasks:
<ul id="list">
<!-- These are dummy values for the unordered list. The idea
is that the next item should be placed beneath them. -->
<li>test1</li>
<li>test2</li>
<li>test3</li>
</ul>
</section>
<script type="text/javascript" src="todo.js">
</script>
</body>
</html>
【问题讨论】:
-
您正在提交表单,这会导致页面重新加载吗?
-
document.createElement将在内存中创建一个元素,但在将其附加到 DOM 之前它不会呈现。您需要以某种方式将entry附加到DOM,即作为主体的子元素或ID 为“main”的元素的子元素等。您也不想提交表单,正如他们所说的^。为此,请使用按钮类型的输入而不是提交类型的输入。 (老实说,您已经有一个 ID 为“list”的列表——只需将新项目附加到该列表中,而不是不必要地创建“条目”。) -
@IsaacVidrine,确实发生了。我想我不知道这样做会发生什么,并认为它会重新加载更改。这里的另一个答案导致这不是我应该拥有的。
-
@IceMetalPunk,我以为我在 JS 文件的倒数第三行代码中附加了
entry。我知道附加到<ul id='list'>标签不起作用,但我不明白为什么它不起作用。关于不要不必要地创建新变量的好点 - 谢谢。我是一个草率的编码员。
标签: javascript html