【问题标题】:How to fetch and display a specific index in a JSON file using a Javascript loop如何使用 Javascript 循环在 JSON 文件中获取和显示特定索引
【发布时间】: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


    【解决方案1】:

    类似的东西

    window.addEventListener("load", (event)=>
      {
      const requestURL      = 'https://byui-cit230.github.io/weather/data/towndata.json'
        ,   divWeathertowns = document.querySelector('div.weathertowns')
        ;
      fetch(requestURL)
      .then( response=>response.json() )
      .then( jsonObject=>
        {
        const towns = jsonObject['towns']
          ;
        for ( let i of [2,4,6] )
          {
          let towninfo = document.createElement('section') 
            , townname = document.createElement('h2')
            ;
          townname.textContent = towns[i].name;
          towninfo.appendChild(townname);
          divWeathertowns.appendChild(towninfo);
          }
        });
      })
    &lt;div class="weathertowns"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多