You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odin Project图书馆项目:未读图书的Read Book按钮不显示问题

问题原因与修复方案

你的问题出在**textContent的使用顺序**上:当你先把readBook按钮添加到bookDetails,再执行bookDetails.textContent = ...时,textContent会替换掉bookDetails内的所有现有内容(包括刚添加的按钮),导致按钮被清除。

修复步骤

把设置图书信息文本的代码移到添加按钮之前,这样后续添加的按钮就不会被覆盖:

修改后的JavaScript代码

let myLibrary = [
  {
    title: "HardCode",
    author: "Sir Not Appearing",
    pages: "infinite",
    read: false,
  },
];

function book(title, author, pages, read) {
  this.title = title;
  this.author = author;
  this.pages = pages;
  this.read = read.toLowerCase() === "y";
}

function addBookToLibrary() {
  const titleInput = document.getElementById("title");
  const authorInput = document.getElementById("author");
  const pagesInput = document.getElementById("pages");
  const readInput = document.getElementById("read");
  const title = titleInput.value;    
  const author = authorInput.value;   
  const pages = pagesInput.value;     
  const readValue = readInput.value;  

  if (title && author && pages && readValue) {
    const newBook = new book(title, author, pages, readValue);
    myLibrary.push(newBook);
    titleInput.value = "";
    authorInput.value = "";
    pagesInput.value = "";
    readInput.value = "";

    displayLibrary();
  }
}

function displayLibrary() {
  const existingLibraries = document.querySelectorAll("div.library");
  existingLibraries.forEach((existingLibrary) => {
    existingLibrary.remove();
  });

  const libraryContainer = document.createElement("div");
  libraryContainer.className = "library";
  libraryContainer.innerText = "Library";

  myLibrary.forEach((book, index) => {
    const bookDetails = document.createElement("div");

    // 先设置图书信息文本,再添加按钮
    bookDetails.textContent = `${book.title} by ${book.author}, ${
      book.pages} pages, ${book.read ? "已读" : "未读"}`;

    const delBook = document.createElement("button");
    delBook.innerText = "删除图书";
    // 此处可添加点击事件监听

    if (!book.read) {
      const readBook = document.createElement("button");
      readBook.innerText = "标记已读";
      // 此处可添加点击事件监听
      bookDetails.appendChild(readBook);
    }

    bookDetails.appendChild(delBook);
    libraryContainer.appendChild(bookDetails);
  });

  document.body.appendChild(libraryContainer);
}
displayLibrary();

补充说明

  • textContent会完全替换元素的所有子节点,包括之前添加的按钮,因此必须调整执行顺序。
  • 若想更灵活控制文本与元素布局,也可使用document.createTextNode()创建文本节点,再通过appendChild添加,避免覆盖已有内容。

内容的提问来源于stack exchange,提问作者Loptr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:35:52