如何在页面刷新时从JSON文件替换书籍名言及作者、书名信息?
实现页面刷新时从JSON加载书籍名言的方法
你需要实现页面刷新时,从JSON文件获取新的书籍名言、作者及书名,替换页面上现有展示区块的内容。你的HTML结构如下:
<section class="piece_book section"> <h3 class="piece_book--title">A Piece of Book</h3> <div class="piece_box"> <p class="piece_book--text"> “It is only with the heart that one can see rightly; what is essential is invisible to the eye.” </p> <div class="piece_book--info"> <p class="piece_book--author">Antoine de Saint-Exupéry</p> <p class="piece_book--name">The Little Prince</p> </div> </div> </section>
实现步骤:
1. 准备JSON数据文件
创建一个名为quotes.json的文件,存入多条名言数据,格式如下:
[ { "quote": "“It is only with the heart that one can see rightly; what is essential is invisible to the eye.”", "author": "Antoine de Saint-Exupéry", "book": "The Little Prince" }, { "quote": "“You have to write the book that wants to be written. And if the book will be too difficult for grown-ups, then you write it for children.”", "author": "Madeleine L'Engle", "book": "A Wrinkle in Time" }, { "quote": "“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”", "author": "Jane Austen", "book": "Northanger Abbey" } ]
2. 添加JavaScript逻辑
在HTML页面的</body>标签前插入以下代码(也可单独存为外部JS文件引入),实现页面加载时获取数据并更新DOM:
// 页面加载完成后执行逻辑 document.addEventListener('DOMContentLoaded', async function() { try { // 请求JSON数据文件 const response = await fetch('quotes.json'); if (!response.ok) { throw new Error('数据请求失败'); } const quotes = await response.json(); // 随机挑选一条名言 const randomIdx = Math.floor(Math.random() * quotes.length); const targetQuote = quotes[randomIdx]; // 获取页面上的DOM元素 const quoteEl = document.querySelector('.piece_book--text'); const authorEl = document.querySelector('.piece_book--author'); const bookEl = document.querySelector('.piece_book--name'); // 更新元素内容 quoteEl.textContent = targetQuote.quote; authorEl.textContent = targetQuote.author; bookEl.textContent = targetQuote.book; } catch (err) { console.error('加载名言出错:', err); // 可选:出错时保留默认内容,或显示自定义提示 } });
注意事项:
- 确保
quotes.json和HTML文件路径对应,同目录下直接写文件名即可 - 本地直接打开HTML(
file://协议)可能被浏览器限制请求,建议用本地服务器(比如VS Code的Live Server插件)测试 - 若不需要随机选择名言,可修改逻辑为按顺序循环或其他规则筛选
内容的提问来源于stack exchange,提问作者Mahdi
相关产品推荐
相关产品推荐

