Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Make按钮单击在LocalStorage中存储API数据_Javascript_Local Storage - Fatal编程技术网

Javascript Make按钮单击在LocalStorage中存储API数据

Javascript Make按钮单击在LocalStorage中存储API数据,javascript,local-storage,Javascript,Local Storage,如何单击按钮将从API检索到的数据存储到localStorage 下面的结果在某种程度上是我想要存储的: function getResults(query) { fetch(`https://cors-anywhere.herokuapp.com/https://api.openweathermap.org/data/2.5/find?q=${query}&units=metric&APPID=XXXXXX`) .then(weather => {

如何单击按钮将从API检索到的数据存储到localStorage

下面的结果在某种程度上是我想要存储的:

function getResults(query) {
    fetch(`https://cors-anywhere.herokuapp.com/https://api.openweathermap.org/data/2.5/find?q=${query}&units=metric&APPID=XXXXXX`)
        .then(weather => {
            return weather.json()
        })
        .then(displayResults)
}

function displayResults(weather) {
    console.log(weather)
    let city = document.querySelector('.cityy')
    city.innerHTML = `${weather.list[0].name}`
    let temp = document.querySelector('.current')
    temp.innerHTML = `${weather.list[0].main.temp}`
    let descr = document.querySelector('.description')
    descr.innerHTML = `${weather.list[0].weather[0].description}`
}
我的纽扣

要将天气响应对象保存到本地存储,您可以将
getResults
函数修改为:

function getResults(query) {
    fetch(`https://cors-anywhere.herokuapp.com/https://api.openweathermap.org/data/2.5/find?q=${query}&units=metric&APPID=XXXXXX`)
        .then(weather => weather.json())
        .then(weather => {
          localStorage.setItem(weather.list[0].name, JSON.stringify(weather));
          return weather;
        })
        .then(displayResults)
}
然后,要检索存储的信息,只需调用
localStorage.getItem
并将其解析回一个对象,如下所示:

displayResults(JSON.parse(localStorage.getItem('name of city')));
更新 第一个响应将API的整个响应存储为对象。要仅存储用户单击“保存”按钮时页面中显示的内容,可以执行以下操作:

document.querySelector('.butt2').addEventListener('click', function(event) {
  const store = {
    city: document.querySelector('.city').innerHTML,
    temp: document.querySelector('.current').innerHTML,
    description: document.querySelector('.description').innerHTML
  };
  localStorage.setItem('saved-by-user', JSON.stringify(store))
});


按钮是否也会触发数据提取?很好,非常感谢,但现在只要按enter键就可以保存数据。。。意味着所有的城市都会被储存起来。我想,要让按钮发挥作用,必须要做eventListener?是的,我相信可能还有更多的东西,你只想在用户单击按钮后存储页面中显示的内容,对吗?您能否添加API的响应,以便我更好地了解您使用的是什么数据?@learnjspde我更新了它,只保存显示的信息,并每次覆盖它。令人惊讶的是,这太棒了,效果非常好。最后,如果不覆盖?干杯如果不想覆盖,只需更改
localStorage.setItem
函数的第一个参数,以便键具有唯一值,而不是字符串
'saved-by-user'
。您可以使用城市的名称(尽管我不确定这是否足以保证唯一性),例如:
localStorage.setItem(store.city,JSON.stringify(store))