我正在尝试创建一个简单的待办事项列表应用程序 JavaScript。我编写的 JavaScript 基本上是从输入元素中获取值并将其传递给几个函数。
我在 CodePen 上创建了一个实时示例,您可以在此处查看:http://cdpn.io/hnBmD
编辑:代码也位于下面吗?
看来appendChild可能会删除父函数正在创建的“li”节点?有人可以给我一个合理的解释吗?
注意:我确实将 JavaScript 放在一个单独的文件中,并且它是在结束正文标记之前加载的。
HTML:
<form>
<p><input type="text" id="inItemText" autofocus><button type="submit" id="submitButton">+</button></p>
</form>
<ul id="toDoList">
</ul>
JavaScript:
// Defining nodes.
var inItemText = document.getElementById("inItemText");
var submitButton = document.getElementById("submitButton");
// Once "enter" is pressed or click event is triggered, execute the function.
// The function below is basically checking the value of the input, to make sure the value is empty. If it isn't, it passes the value and the "ul" element node into the addNewItem function.
submitButton.onclick = function(){
var itemText = inItemText.value;
if (itemText == "" || itemText == " ") {
return false;
} else {
addNewItem(document.getElementById("toDoList"), itemText);
}
}
// Once the parameters are passed. This basically creates a "li" element, applies the value of the input element into the innerText of the "li" element created and then appends the "ul" with the "li" we just created. Also, it resets the value of the input so we can enter another checklist item in.
function addNewItem(list, itemText) {
var listItem = document.createElement("li");
listItem.innerText = itemText;
list.appendChild(listItem);
itemText = inItemText.value = "";
}
谢谢!
最佳答案
在调用 addNewItem
后,您需要从 onclick
函数返回 false
。否则,它将提交表单,并重新加载页面。
submitButton.onclick = function(){
var itemText = inItemText.value;
if (itemText == "" || itemText == " ") {
return false;
} else {
addNewItem(document.getElementById("toDoList"), itemText);
return false;
}
}
或更简单地说:
submitButton.onclick = function(){
var itemText = inItemText.value.trim();
if (itemText !== "" || itemText == " ") {
addNewItem(document.getElementById("toDoList"), itemText);
}
return false;
}
或者,正如其中一条评论所建议的那样,删除表单,然后就无需提交任何内容。
关于javascript - appendChild 可能删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123387/