从对象拉取结果时如何在HTML中实现数据逻辑分组
解决方案
1 调整HTML结构
把你页面中原来三个独立存放作者、标题、描述的列表容器,替换为一个统一的书籍列表容器即可:
<!-- 替换掉原来的三个ul节点 --> <div class="book-list"></div>
2 修改JS逻辑
核心改动是遍历每本图书时,先创建单独的div容器存放当前本书的所有信息,再把这个div插入到全局的书籍列表中,同时添加字段兼容逻辑避免缺失字段时显示undefined:
const searchButton = document.getElementById('searchbtn') const form = document.getElementById('myform') // 替换原来的三个节点选择,改为选择全局书籍列表 const bookList = document.querySelector('.book-list') document.addEventListener("DOMContentLoaded", () => { searchButton.addEventListener('click', e => { e.preventDefault() // 每次搜索前清空上次的搜索结果,避免结果叠加 bookList.innerHTML = '' const inputSearch = document.getElementById('books').value const bookUrl = ('https://www.googleapis.com/books/v1/volumes?q=' + inputSearch) fetch(bookUrl) .then (res => res.json()) .then (obj => { obj.items.forEach((book, index) => { // 创建单本书的容器div const bookCard = document.createElement('div') bookCard.className = 'book-card' // 创建当前本书的各个信息节点 const listAuthor = document.createElement('p') const listTitle = document.createElement('h3') const listDescription = document.createElement('p') // 兼容字段缺失的情况 listAuthor.innerText = book.volumeInfo.authors || '暂无作者信息' listTitle.innerText = book.volumeInfo.title || '暂无标题' listDescription.innerText = book.volumeInfo.description || '暂无简介' // 把三个信息节点插入到当前书的容器中 bookCard.appendChild(listTitle) bookCard.appendChild(listAuthor) bookCard.appendChild(listDescription) // 把单本书容器插入到全局列表中 bookList.appendChild(bookCard) }) form.reset() }) }) })
可选优化:添加卡片样式
你可以给单书容器添加CSS样式,展示效果更直观:
.book-card { border: 1px solid #eee; border-radius: 8px; padding: 16px; margin-bottom: 12px; } .book-card h3 { margin: 0 0 8px 0; color: #333; } .book-card p:nth-of-type(1) { color: #666; font-size: 14px; margin: 0 0 12px 0; } .book-card p:nth-of-type(2) { color: #888; font-size: 14px; line-height: 1.5; margin: 0; }
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

