尝试构建货币转换器应用程序,但我在向选择元素添加选项时遇到问题。我想在选项中包含名称(美元)和值(value)(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);
})
})
最佳答案
您的中有一些错误。然后
尝试下面的选项,它会在选项中显示名称+值
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>
关于javascript - 向对象中的选择添加选项? (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46755172/