繁体   English   中英

将选项添加到对象的选择中? (JS)

[英]Adding options to a select from an object? (JS)

尝试构建货币转换器应用程序,但是在向select元素添加选项时遇到了麻烦。 我想在选项中输入名称(USD)和值(1.23)。 我试图将对象转换为数组以使用map,但似乎没有用。

任何帮助将不胜感激。

的HTML

<div id="msg"></div>
<input type="number" autofocus id="input">
<select id="rateFrom">
</select>
 <hr>
<input type="number" disabled id="output">
<select id="rateTo">
</select>

JS

const select = document.getElementById('rateFrom'); 
const url = 'https://api.fixer.io/latest?base=USD'; // get currency rates
fetch(url)
.then(response => {
    if (response.status !=200) {
        document.getElementById('msg').innerHTML=`<p>SYSTEM IS OFFLINE 
(${response.status})</p>`
    }else{
        return response.json();
    }
})
.then(data => {
    console.log(data);
 document.getElementById('msg').innerHTML=`<p>SYSTEM IS ONLINE (LAST UPDATE 
 WAS @ ${data.date})</p>`
 let rates = data.rates;
 console.log(rates);
 rates = Object.keys(rates).map(function (key) {  //convert object to array
 return { [key]: rates[rates] };
 })
 console.log(rates);
 return rates.map(function(rate) { // map through the rates and for each run 
 the code below


let el = document.createElement("option");
 el.textContent = rate;
 el.value = rate;
 select.appendChild(el);
 })
 })

使用select.add(el); 而不是select.appendChild(el);

尝试以下代码以形成所需的适当数据结构。

rates = Object.keys(rates).map(function (key) { 
            return { [key]: rates[key] } 
     });

在您的HTML附加部分中,

let currentKey = Object.keys(rate)[0]; 

el.textContent = currentKey;

el.value = rate[currentKey];

希望能有所帮助。

你有一些号码在你的错误.then尝试在选项下方显示名称+值

 const select = document.getElementById('rateFrom'); const url = 'https://api.fixer.io/latest?base=USD'; // get currency rates fetch(url) .then(response => { if (response.status !=200) { document.getElementById('msg').innerHTML=`<p>SYSTEM IS OFFLINE (${response.status})</p>` }else{ return response.json(); } }) .then(data => { document.getElementById('msg').innerHTML=`<p>SYSTEM IS ONLINE (LAST UPDATE WAS @ ${data.date})</p>` let rates = data.rates; // data from url doesn't have USD 1.23 like you mentioned in your question, // but if you want to add it manually do this: let usdOption = document.createElement("option"); usdOption.value = 'USD'; usdOption.textContent = 'USD '+1.23; select.add(usdOption) // populating options with data from the url Object.keys(rates).map(function (key) { let el = document.createElement("option"); el.value = key; el.textContent = key + ' ' + rates[key]; select.add(el) }) }) 
 <div id="msg"></div> <input type="number" autofocus id="input"> <select id="rateFrom"> </select> <hr> <input type="number" disabled id="output"> <select id="rateTo"> </select> 

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM