通过javascript创建节点抛出类型错误:'。appependChild不是函数'

时间:2016-11-10 03:28:28

标签: javascript

我知道还有其他看似重复的帖子,但我无法解决我的问题。这是我关于stackoverflow的第一个代码和第一个问题。请为将来的问题提供任何相关的建议。

我正在尝试为类项目创建待办事项列表。首先,我不明白为什么在单击“添加”按钮之前出现错误“appendChild不是函数”。浏览器在调用之前是否运行了函数?其次,我无法使用querySelector或甚至getElementById(js第1-3行)将变量初始化为DOM的元素,只有getElementsByClassName有效。最重要的是,我需要用appendChild来解决问题。

我希望你发现这个HTML像我在开始js部分和挫折之前所做的那样滑稽。

<html>
<head>
  <title>Larry David's Election Day To Do List</title>
  <link rel="stylesheet" href="firstMiniCSS.css"></link>
  <meta charset="utf-8">
</head>

<script src="firstMiniJS.js"></script>

<body>
<h1>Larry David's Election Day To Do List</h1>
<h2>Because voting is impossible when you're Larry David...</h2>

<div class= "toDoList">
  <p>To Do List:</p>
  <ul class="list" id="list">
    <li>Wake up... early. less people vote in the morning</li>
    <li><del datetime="11-08-2016">Check the mail</del> don't check the mail</li>
    <li>Find inconspicuous clothes</li>
    <ul>
      <li>Definitely a hat</li>
    </ul>
    <li>Coffee with whole milk. None of this 2% crap</li>
    <li>Call Richard to ask who he's voting for</li>
    <li>Remember it's very important to vote. You must vote Larry.</li>
    <li>Bring a pen</li>
  </ul>
  <label for="addField">Add something to the list: </label><input type="text" class="addField" placeholder="What would Larry do?"><input type="submit" value="Add" class="addSubmit">
</div>

</body>
</html>

的javascript:

var addField = document.getElementsByClassName('addField');
var submitTask = document.getElementsByClassName('addSubmit');
var list = document.getElementsByClassName('list');

var listedTasks = [];

function createTask() {
  if(addField !== ''){
    listedTasks.unshift(addField.value);

    for(var i = 0; i < listedTasks.length; i++) {
      taskText = listedTasks[i];
      var newTask = document.createElement('li');
      newTask.innerHTML = taskText;
      list.appendChild(newTask);
    }
  }
}
submitTask.addEventListener('click', createTask());

由于

0 个答案:

没有答案