用JavaScript遍历API数据 在DOM展示REST Countries搜索的多个匹配项
问题修复方案
现存问题本质
- DOM覆写逻辑冲突:
createCountryCard函数内部直接对main.innerHTML赋值,每次赋值都会清空<main>标签下的全部内容。循环遍历所有匹配国家时,前一个国家的卡片会被后一个的内容完全覆盖,最终页面只能渲染最后一个搜索结果。 - 字段读取无容错:部分国家的首都、货币、语言字段可能为空值或空数组,直接按索引读取对象属性时就会输出
undefined,甚至触发渲染报错。
具体修改步骤
- 调整数据请求后的渲染逻辑:先清空容器内的旧内容,遍历所有匹配项时拼接完整的卡片HTML字符串,最后一次性插入DOM,避免循环内反复覆写:
async function getCountryData(name) { try { const { data } = await axios.get(APIURL + name) // 清空原有容器内容 main.innerHTML = '' // 拼接所有匹配国家的卡片HTML let totalHTML = '' data.forEach(countryItem => { totalHTML += createCountryCard(countryItem) }) // 一次性渲染全部内容 main.innerHTML = totalHTML } catch (err) { if(err.response.status == 404) { main.innerHTML = '' createErrorCard('No countries found') setTimeout(() => { main.innerHTML = '' }, 1500); } } } - 重构
createCountryCard函数:不再直接操作DOM,仅返回拼接好的卡片字符串,同时给可能为空的字段加兜底值,避免出现undefined:function createCountryCard(country) { // 空字段兜底 const capital = country.capital || '暂无首都信息' const popText = country.population?.toLocaleString('en') || '暂无人口数据' const currencyText = country.currencies?.[0] ? `${country.currencies[0].name} ${country.currencies[0].symbol}` : '暂无货币信息' const langText = country.languages?.[0]?.name || '暂无语言信息' const timezoneText = country.timezones?.join(', ') || '暂无时区信息' return ` <div class="content-container"> <div class="card"> <div class="wrapper"> <div class="card-title"> <h2>${country.name}</h2> <h4>Capital: ${capital}</h4> <h5>Population: ${popText}</h5> </div> <div class="card-image"> <img src="${country.flag}" alt="${country.name +'-flag'}" /> </div> </div> <div class="wrapper"> <div class="map-content"> <div class="google-map"></div> </div> <div class="card-content"> <ul class="card-list"> <li><strong>Region:</strong> ${country.region || '暂无区域信息'}</li> <li><strong>Subregion:</strong> ${country.subregion || '暂无次区域信息'}</li> <li><strong>Currency:</strong> ${currencyText}</li> <li><strong>Spoken Language:</strong> ${langText}</li> <li><strong>Timezone:</strong> ${timezoneText}</li> </ul> </div> </div> </div> </div> ` } - 细节优化:原代码中每个卡片都带
id="map"的属性,会导致页面出现重复id,直接改成类名即可避免后续地图功能的冲突;搜索提交后可以保留输入框的已有内容,方便用户调整搜索关键词,不需要主动清空。
内容的提问来源于stack exchange,提问作者Matt Davis
相关产品推荐
相关产品推荐

