如何使用JavaScript渲染本地JSON数据生成指定结构的列表
问题分析与解决方案
你的核心问题是未正确遍历cities数组——block.cities是数组类型,无法直接通过block.cities.wikiLink访问单个城市属性,必须遍历数组生成列表项。另外你拆分两个数据文件的方式,会导致后续新增国家时需要修改JS代码,不符合“添加数据自动显示”的需求,建议合并为单个JSON文件。
1. 合并数据到单个JSON文件
创建countries.json(注意JSON键必须用双引号):
[ { "country": "England", "cities": [ { "wikiLink": "https://en.wikipedia.org/wiki/London", "citiesName": "London", "citiesDescription": "is the capital and largest city of England and the United Kingdom, with a population of just under 9 million" }, { "wikiLink": "https://en.wikipedia.org/wiki/Liverpool", "citiesName": "Liverpool", "citiesDescription": "Is a city and metropolitan borough in Merseyside" } ] }, { "country": "Iceland", "cities": [ { "wikiLink": "https://en.wikipedia.org/wiki/Reykjav%C3%ADk", "citiesName": "Reykjavík", "citiesDescription": "It is located in southwestern Iceland, on the southern shore of Faxaflói bay." } ] } ]
2. 修正模板函数与渲染逻辑
编写嵌套模板函数,分别处理城市列表项和国家区块:
// 生成单个城市的列表项 function cityTemplate(city) { return ` <li class="list__item"> <a class="list__link" href="${city.wikiLink}" target="_blank"> <span class="gradient__text">${city.citiesName}</span> - ${city.citiesDescription} </a> </li> `; } // 生成单个国家的完整区块 function countryTemplate(country) { return ` <div class="section"> <h2 class="title">${country.country}</h2> <ul class="list"> ${country.cities.map(cityTemplate).join('')} </ul> </div> `; } // 读取JSON并渲染到页面 fetch('./countries.json') .then(res => res.json()) .then(data => { const contentContainer = document.querySelector('.content'); contentContainer.innerHTML = data.map(countryTemplate).join(''); }) .catch(err => console.error('数据加载失败:', err));
3. 页面容器准备
确保HTML中存在目标容器:
<div class="content"></div>
关键修正点
- 原代码直接访问
block.cities.wikiLink,但block.cities是数组,必须用map遍历才能获取每个城市的属性。 - 合并为单个JSON文件后,后续新增国家只需往JSON中添加新的对象,无需修改JS代码,实现“添加数据自动显示”的需求。
内容的提问来源于stack exchange,提问作者dvoit
相关产品推荐
相关产品推荐

