简体   繁体   English

如何将获取数据存储到以后可以访问的全局变量中?

[英]How to store fetch data into a global variable that you can access later?

I have this code below that's pulling all of one specific product type and the array has data that i want to use in a different function.我在下面有这段代码,它提取了所有一种特定的产品类型,并且该数组包含我想在不同的 function 中使用的数据。 How would i go about storing the fetched data into a variable that i can pull into a different function(i need to add a click event and filter to display additional information from this array elsewhere)我将如何 go 将获取的数据存储到一个我可以拉入不同函数的变量中(我需要添加一个点击事件和过滤器以在其他地方显示来自该数组的其他信息)

const displayProduct = (event) => {
    const info =document.getElementById('info')
    const ul = document.getElementById('makeup-list')
    ul.innerHTML = " "
     fetch( `https://makeup-api.herokuapp.com/api/v1/products.json/?product_type=${event.target.value}`)
    .then(res => res.json())
    //iterate
    .then(data => {
        data.forEach(data => {
           info.innerHTML += 
           
          ` <li><a href="#"  data-id=>${data.name}</a></li>`

                

        
        })

You can use localStorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage您可以使用 localStorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Save in localStorage:保存在本地存储中:

ul.innerHTML = " "
 fetch( `https://makeup-api.herokuapp.com/api/v1/products.json/?product_type=${event.target.value}`)
.then(res => res.json())
//iterate
.then(data => {
    localStorage.setItem('myData', data);
 ....
}

Get the data in another func:在另一个函数中获取数据:

const data = localStorage.getItem('myData');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将获取的数据存储在变量中以供以后访问 - Store fetch data in variable to access it later Javascript如何将Fetch数据存储到全局变量 - Javascript how to store Fetch data to a global variable 如何将数据存储在全局变量中以在应用程序中访问它? - How to store data in a global variable to access it with in application? 如何将$ .getJSON对象存储在全局变量中并在以后导航 - How to store $.getJSON object in global variable and navigate through it later 当用户点击一个按钮时,你如何存储一个以后可以使用的变量? - When a user clicks a button, how do you store a variable that can be used later? 如何将数据存储到jQuery Datatable中的javascript全局变量 - How can I store data to javascript global variable in jquery Datatable 如何将数据存储在全局变量中? - how can I store my data in a global variable? 您如何将 getText 的结果存储在变量中以供以后在 Nightwatch 中使用? - How do you store the result of getText in a variable to use later on in Nightwatch? 如何将 fetch API 请求中的 json 数据存储到全局变量中 - javascript - How to store the json data from fetch API request into a global variable - javascript 您如何存储一个更改为可以在任何地方传递的全局变量的 innerHTML? - How can you store an innerHTML that changes into a global variable that can be passed everywhere?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM