javascript - appendChild 可能删除元素?

标签 javascript html

我正在尝试创建一个简单的待办事项列表应用程序 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;
      }
}

DEMO

或更简单地说:

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/

相关文章:

javascript - Jquery Tablesorter 过滤器和外部选择框

Javascript/jQuery 将不同的函数参数附加到 .click() 方法

javascript - 如何在 d3 中以编程方式调用 "click"事件?

javascript - 如何判断数组中哪个元素被移动了?

javascript - Jquery 菜单和 Logo 切换

javascript - 文本区域字段在提交时返回空

javascript - 如何创建一个对 Javascript 中先前函数生成的内容使用react的函数

javascript - 为什么我无法将单击事件添加到动态插入的列表元素?

html - 在 CSS 中将子级菜单放置在其父级旁边

html - 为什么 "height: auto;"在我使用 "float:left"时不起作用?