簡體   English   中英

如何使用 JSON 和 Fetch/Async Await 將數據從數組/對象添加到 HTML 下拉菜單

[英]How to add data from array/Object to the HTML drop down menu using JSON and Fetch/Async Await

我想將貓的名字添加到下拉菜單中。 我可以訪問屬性及其值。 但是,當我嘗試在菜單中輸入/放置這些值時,只有最后一個值被存儲。 我假設它是(代碼 - Function accessArray)一旦它循環遍歷整個事物就會替換當前值。 控制台日志(數據)

data.name 包含貓的名字列表。 控制台日志(元素名稱)

我想創建一個列表,以便在下拉菜單中包含所有貓的名稱。 落下

這是我正在使用的公共 API 的鏈接 - https://docs.thecatapi.com/api-reference/breeds/breeds-list

async function start(){
   try{
    const response = await fetch("https://api.thecatapi.com/v1/breeds");
    const data = await response.json();
    console.log (data);
    filterData(data);
   }catch (e){
    console.log("Error : "+ e);
   }
}
start();


function filterData (data){
    data.forEach(element => {
        console.log(element.name);
        acessArray(element.name);
    });
}


function acessArray(data){
    document.getElementById("catList").innerHTML = `
    <select>
        <option value="Choose a cat">Choose a cat</option>
        <option> ${data} </option>            
    </select>
    `;
}

不確定你想要你的代碼做什么,但如果它只是<option>那么你會弄清楚的。

每次設置此document.getElementById("catList").innerHTML = '<select>...</select>'時,您都會覆蓋最后一次輸入。

查看代碼並替換您需要的內容。

async function start(){
   try{
    const response = await fetch("https://api.thecatapi.com/v1/breeds");
    const data = await response.json();
    console.log (data);
    filterData(data);
   }catch (e){
    console.log("Error : "+ e);
   }
}
start();


function filterData (data){
    document.getElementById("catList").innerHTML = ''; // clear the list
    data.forEach(element => {
        console.log(element.name);
        acessArray(element.name);
    });
}


function acessArray(data){
    // This will add a <select> over another <select> and so on
    document.getElementById("catList").innerHTML += `
    <select>
        <option value="Choose a cat">Choose a cat</option>
        <option> ${data} </option>            
    </select>
    `;
}

我認為它應該做什么:

async function start(){
   try{
    const response = await fetch("https://api.thecatapi.com/v1/breeds");
    const data = await response.json();
    console.log (data);
    filterData(data);
   }catch (e){
    console.log("Error : "+ e);
   }
}
start();


function filterData (data){
    document.getElementById("catList").innerHTML = `
    <select>
       <option value="Choose a cat">Choose a cat</option>
  `; // clear the list and start filling
    data.forEach(element => {
        console.log(element.name);
        acessArray(element.name);
    });
    document.getElementById("catList").innerHTML += '</select>'; //End

}


function acessArray(data){
    // This will add a <select> over another <select> and so on
    document.getElementById("catList").innerHTML += `
        <option> ${data} </option>            
    `;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM