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

基于JavaScript面向对象的图书馆书籍表格自动填充技术咨询

图书馆项目表格填充解决方案

先修正HTML的ID冲突问题

原代码里表单输入框和表格单元格重复使用title/author/pages作为ID,这会导致DOM查询出错,先修改表格结构,给表格加唯一ID,去掉重复的单元格ID:

<table id="bookTable">
    <tr>
        <th>Title</th>
        <th>Author</th>
        <th>Pages</th>
    </tr>
    <!-- 表格行后续由JS动态生成 -->
</table>

重构JavaScript代码

把逻辑拆分为Book(单本书籍数据)和Library(书籍管理+UI更新)两个构造函数,用this引用实例属性,实现创建书籍时自动填充表格:

// 单本书籍的构造函数
function Book(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
}

// 图书馆管理类,负责书籍存储和表格更新
function Library() {
    this.books = []; // 存储所有书籍的数组

    // 添加书籍并自动更新表格
    this.addBook = function(title, author, pages) {
        const newBook = new Book(title, author, pages);
        this.books.push(newBook);
        this.updateTable(); // 添加完成后立即更新表格
        return newBook;
    };

    // 表格更新方法,用this引用当前实例的书籍列表
    this.updateTable = function() {
        const table = document.getElementById('bookTable');
        // 清空表头以外的旧行
        while (table.rows.length > 1) {
            table.deleteRow(1);
        }

        // 遍历书籍数组,生成新行
        this.books.forEach(book => {
            const row = table.insertRow();
            // 填充单元格数据,直接引用book实例的属性
            row.insertCell().textContent = book.title;
            row.insertCell().textContent = book.author;
            row.insertCell().textContent = book.pages;
        });
    };
}

// 初始化图书馆实例
const myLibrary = new Library();

// 创建书籍时自动填充表格
myLibrary.addBook("Cat and hat", "Bob", 150);
myLibrary.addBook("The Little Prince", "Antoine de Saint-Exupéry", 96);

// 处理表单提交,添加新书籍
document.getElementById("submit").addEventListener("click", function(event) {
    event.preventDefault();
    const title = document.getElementById("title").value;
    const author = document.getElementById("author").value;
    const pages = document.getElementById("pages").value;
    
    if (title && author && pages) {
        myLibrary.addBook(title, author, parseInt(pages));
        // 清空表单输入
        document.getElementById("title").value = "";
        document.getElementById("author").value = "";
        document.getElementById("pages").value = "";
    }
});

关键说明

  • 用this实现数据引用:Library类中this.books指向当前实例的书籍数组,updateTable方法通过遍历这个数组填充表格;每个Book实例的属性(title/author/pages)都是通过构造函数里的this定义的,直接引用即可。
  • 自动填充逻辑:每次调用addBook添加书籍后,立刻执行this.updateTable(),实现创建书籍时表格自动更新。
  • 静态展示书籍:表格会根据books数组动态生成所有书籍行,只要数组里有数据,页面刷新后重新初始化实例就能展示(如果需要持久化可以结合localStorage,当前代码已满足静态展示需求)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:40:14