【发布时间】:2021-02-23 00:34:35
【问题描述】:
我目前正在使用 javascript 中的 fetch 从另一个站点获取信息到我自己的站点中。我遇到的问题是,我正在使用循环将 JSON 文件的所有索引显示到我的站点中。我实际上想要显示特定的索引,而不是全部,例如索引 2,4 和 6。
到目前为止,这是我的代码:
window.addEventListener("load", (event)=>{
const requestURL = 'https://byui-cit230.github.io/weather/data/towndata.json';
fetch(requestURL)
.then(function (response) {
return response.json();
})
.then(function (jsonObject) {
const towns = jsonObject['towns'];
for (let i = 0; i < towns.length; i++ ) {
let towninfo = document.createElement('section');
let townname = document.createElement('h2');
townname.textContent = towns[i].name;
towninfo.appendChild(townname);
document.querySelector('div.weathertowns').appendChild(towninfo);
}
});
})
这显示了所有参考城镇,但我只想显示 3 个特定城镇的标题。关于如何进行此操作的任何建议?
【问题讨论】:
标签: javascript arrays json loops fetch