为什么这个 JavaScript 代码没有执行?

Why isn't this JavaScript code executing?

抱歉,我是一名学生,我无法弄清楚我的代码有什么问题!当我单击按钮时,绝对没有任何反应。我已经尝试隔离每个功能,但仍然没有任何反应。多年来我一直在寻找它,试图找到缺少的标签或缺少的括号或括号或其他东西,但我没有找到它。它旨在创建一个迷你博客模拟。您应该能够使用第一个函数将条目添加到列表顶部,并且您应该能够使用第二个函数删除您选择的条目。感谢您的帮助!

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Chapter 5 Activity</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <h1>Awesome NBA Blog!  Each day, a sentence about the feats of a different legend!</h1>
    <ol id="playerEntries">
      <li>Michael Jordan: 6 Championship rings in 6 NBA Finals appearances.</li>
      <li>Bill Russell: 11 time champion in a 13 year career, including one as a player/head coach.</li>
      <li>Kobe Bryant: 5 Championships, 18-time All-Star.</li>
      <li>Lebron James: Won a Championship and was the Finals MVP with 3 different teams.</li>  
    </ol>
    <form action="">
      Add a new entry:
      <input type="text" name="newEntry" id="newEntrySpot" size="80">
      <input type="submit" value="Submit" onclick="addEntry()"><br>
      Delete an entry(which entry would you like to delete?)
      <input type="number" name="entryNum" id="numToDelete">
      <input type="button" value="Delete" onclick="deleteEntry()"><br>
    </form> 
    <script type="text/javascript">
      function addEntry() {
        var newEntry = document.getElementById("newEntrySpot").value;
        var newestEntry = document.createElement("li");
        newestEntry.innerHTML = newEntry;
        var blogList = document.getElementsByTagName("ol")[0];
        var topEntry = document.querySelectorAll("#playerEntries li")[0];
        blogList.insertBefore(newestEntry, topEntry);
        }
        
      function deleteEntry() {
        var num2Delete = document.getElementsByName("entryNum")[0].value;
        var blogList = document.getElementsByTagName("ol")[0];
        var howManyEntries = blogList.length;
        if (howManyEntries >= 1) {
          var postToDelete = blogList[num2Delete - 1];
          var deletedPost = blogList.removeChild(postToDelete);
          }
        }
    </script>
  </body>
</html>

你必须更换

 <input type="submit" value="Submit" onclick="addEntry()"><br>

 <input type="button" value="Submit" onclick="addEntry()"><br> 

否则将提交表单并重新加载页面。您也可以使用表单的提交功能,但您是否必须使用 preventDefault。

另外,为了使 deleteEntry 函数起作用,您不能使用 document.getElementsByTagName("ol")[0];,因为您不能在元素上使用 .length。这是另一种方法:

        function deleteEntry() {
            var num2Delete = document.getElementsByName("entryNum")[0].value;
            var blogList = document.querySelectorAll("ol > li");
            var howManyEntries = blogList.length;

            if (howManyEntries >= 1) {
                var postToDelete = blogList[num2Delete - 1];
                postToDelete.remove();
            }
        }