(JavaScript)尝试使用 createElement() 和 createTextNode() 将项目添加到列表中,但它打印了两次。有没有办法来解决这个问题? [关闭]

问题描述 投票:0回答:0

我正在编写一个程序来制作一个用户可以添加的书籍列表,以跟踪他们想要阅读的书籍。我正在使用 createElement() 和 createTextNode() 来执行此操作。我已经定义了我需要的所有变量,除了一件事,它工作得很好:每次我按下按钮运行它时,函数都会添加两个相同的元素,而不是我想要的单个元素。

我真的很感激能帮我解决这个问题。我正在使用 replit.com,如果有帮助的话。

对不起,如果这是一个愚蠢的问题,我还在学习。提前致谢。

// listens for a click on the "add new" button
document.getElementById("new").addEventListener("click", newBook);
let newdiv = document.getElementById("newdiv");

// takes information about a new list item
function newBook() {
  // reveals the input boxes needed
  newdiv.style.display = "inline-block";
}

// listens for a click on the "add" button
document.getElementById("enternew").addEventListener("click", addItem);

// creates a new list item and adds it to the body of the webpage
function addItem() {
  // defines the new element as an h2 element
  let item = document.createElement("h2");
  //item.type = "checkbox";

  // gets the variable values from the user's input
  let bookname = document.getElementById("book").value;
  let authorname = document.getElementById("author").value;
  let seriesname = document.getElementById("series").value;

  // converts the user's input into text nodes
  let b = document.createTextNode(bookname);
  let a = document.createTextNode(", by " + authorname);
  let s = document.createTextNode(" (" + seriesname + ")");

  // appends the text nodes to the h2 element
  item.appendChild(b);
  item.appendChild(a);
  item.appendChild(s);

  // adds the h2 element, including all the text nodes, to the body of the webpage
  document.body.appendChild(item);
}
javascript html css createelement createtextnode
© www.soinside.com 2019 - 2024. All rights reserved.