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

求助:点击提交按钮后JavaScript数组数据无法在HTML表格显示

问题排查:表单提交后数据无法显示到表格中

手动添加数据能正常显示在表格里,但通过form表单提交的新数据无法显示;点击提交按钮页面会跳转到目标页面,且addToHTML()函数放在submitButton()外能正常运行,移到内部就失效且无报错。


代码文件

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="style.css">
    <title>Book Object</title>
</head>

<body>
    <h1>Book template</h1>

    <form>
        <table id="book-table">
            <thead>
                <tr>
                    <th> Title </th>
                    <th> Author </th>
                    <th> Pages </th>
                    <th> Read </th>
                </tr>
            </thead>

            <tbody id="tbody">
                <tr id="dataContainer"></tr>
            </tbody> 
        </table>
    </form>

    <a href="addbook.html">
        <button id="add-book"> Add Book </button>
    </a>

    <script type="text/javascript" src="script.js"></script>
</body>
</html>

script.js

// Main Book object model
function Book(title, author, pages, read) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.read = read;  
}

// Library object model
function Library() {
    this.myLibrary = [];
    
    this.addToLibrary = function(book) {
        this.myLibrary.push(book);
    }

    // 从localStorage加载数据
    this.loadFromStorage = function() {
        const storedData = localStorage.getItem('library');
        if (storedData) {
            const parsedData = JSON.parse(storedData);
            // 把JSON对象转回Book实例
            this.myLibrary = parsedData.map(item => new Book(item.title, item.author, item.pages, item.read));
        }
    }

    // 保存数据到localStorage
    this.saveToStorage = function() {
        localStorage.setItem('library', JSON.stringify(this.myLibrary));
    }
}

// Create new library object
let library = new Library();

// 加载本地存储的数据
library.loadFromStorage();

// 如果是首次加载,添加初始书籍
if (library.myLibrary.length === 0) {
    // Create new book object
    let book1 = new Book('Awaken the Giant Within', 'Tony Robbins', '351', 'already read');
    let book2 = new Book('Think and Grow Rich', 'Napoleon Hill', '271', 'currently reading');
    let book3 = new Book('Rich Dad Poor Dad', 'Robert T. Kiyosaki', '289', 'finish read');
    let book4 = new Book('Atomic Habits', 'James Clear', '279', 'finish read');
    let book5 = new Book('The Outliers', 'Malcom Gladwell', '311', 'currently reading');

    // Add books to the empty array
    library.addToLibrary(book1);
    library.addToLibrary(book2);
    library.addToLibrary(book3);
    library.addToLibrary(book4);
    library.addToLibrary(book5);
    library.saveToStorage();
}

// Function to add main Book to HTML content
function addToHTML() {
    let tbody = document.querySelector('#tbody');
    // 先清空tbody避免重复渲染
    tbody.innerHTML = '';
    for (let i=0; i < library.myLibrary.length ; i++ ) {
            let content = 
                `<tr>
                    <td> ${library.myLibrary[i].title} </td>
                    <td> ${library.myLibrary[i].author} </td>
                    <td> ${library.myLibrary[i].pages} </td>
                    <td> ${library.myLibrary[i].read} </td>
                </tr>`

            tbody.innerHTML += content;
    }
}

// 页面加载时渲染数据
if (document.querySelector('#tbody')) {
    addToHTML();
}

// Submit button

// Add event listener to submit button
function submitButton() {
    let submit = document.getElementById('submit');
    submit.addEventListener('click', function(event) {
        // 阻止表单默认提交行为
        event.preventDefault();
        
        let jsTitle = document.getElementById('title').value;
        let jsAuthor = document.getElementById('author').value;
        let jsPages = document.getElementById('pages').value;
        let jsRead = document.getElementById('read').value;

        let newBook = new Book(jsTitle, jsAuthor, jsPages, jsRead);
        library.addToLibrary(newBook);
        // 保存数据到本地存储
        library.saveToStorage();
        // 手动跳转到index.html
        window.location.href = 'index.html';
    })
}

addbook.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Book Form</title>
    <link rel="stylesheet" href="addbookform.css">
</head>

<body onload="submitButton()">
    <h1>Add Book Form</h1>
    
    <form>
            <p>Title:</p>
              <input type='text' name='title' id='title' required>
    
            <p>Author: </p>
              <input type='text' name='author' id='author' required>
    
            <p>Pages:</p>
              <input type='number' name='pages' id='pages' required>

            <p>Read:</p>
              <input type='text' name='read' id='read' required>

            <br/>
            <input type='submit' name='submit' value='submit' id='submit'>
    </form>
    <script type="text/javascript" src="script.js"></script>

</body>
</html>

问题根源与解决说明

  1. 表单默认提交导致数据丢失:原代码中form的action和method会触发浏览器默认跳转,此时addbook页面的library对象是页面级的,跳转后index.html会重新加载script.js并初始化新的library,新添加的数据根本带不过去。通过event.preventDefault()阻止默认行为,手动处理跳转前的数据存储。
  2. 数据未持久化:使用localStorage存储图书馆数据,确保页面刷新或跳转后能读取到之前添加的内容。
  3. 重复渲染问题:修改addToHTML()函数,每次渲染前清空tbody,避免重复添加相同数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:25:30