You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS汇率转换程序中从API获取并显示货币全称

解决汇率转换程序显示货币全称的问题

核心问题分析

当前代码仅在渲染下拉选项时临时使用了货币全称,未持久化存储这些数据,导致转换结果无法调用全称;同时转换结果的数值显示存在错误(直接复用了输入值而非转换后的值),需一并修正。

解决方案步骤

  1. 全局存储货币数据:声明全局变量保存API返回的完整货币映射,方便后续随时调用全称。
  2. 优化下拉选项显示(可选):在下拉框中同时展示货币缩写和全称,提升用户识别效率。
  3. 替换结果文本为全称:在转换成功的回调中,通过货币缩写从全局数据中匹配对应全称,替换到结果展示的span和h1标签中。

修改后的完整代码

const before = document.querySelector("span")
const after = document.querySelector("h1")
const input = document.querySelector("input")
const select = document.querySelectorAll("select")
const converted = document.querySelector("#converted")
const convertBtn = document.querySelector("button")
// 全局变量存储货币数据,用于后续获取全称
let currencyData = {};

fetch("https://api.frankfurter.app/currencies")
  .then(data => data.json())
  .then(data => {
    currencyData = data;
    display(data);
  })

// 生成货币下拉选项
const display = data => {
  const currencies = Object.entries(data)
  for (let i = 0; i < currencies.length; i++) {
    // 选项同时显示缩写和全称,用户更易识别
    select[0].innerHTML += `<option value="${currencies[i][0]}">${currencies[i][0]} - ${currencies[i][1]}</option>`
    select[1].innerHTML += `<option value="${currencies[i][0]}">${currencies[i][0]} - ${currencies[i][1]}</option>`
  }
}

// 转换按钮点击事件
convertBtn.addEventListener("click", () => {
  let filledCurrency = select[0].value
  let wantedCurrency = select[1].value
  let value = input.value

  if (filledCurrency !== wantedCurrency) {
    convert(filledCurrency, wantedCurrency, value)
  } else {
    alert("不能选择相同的货币")
  }
})

// 转换逻辑
const convert = (filledCurrency, wantedCurrency, value) => {
  const host = "api.frankfurter.app"
  fetch(
      `https://${host}/latest?amount=${value}&from=${filledCurrency}&to=${wantedCurrency}`
    )
    .then(res => res.json())
    .then(res => {
      const convertedValue = Object.values(res.rates)[0];
      converted.value = convertedValue;
      // 替换为货币全称,可选择是否保留缩写
      before.textContent = `${input.value} ${currencyData[filledCurrency]} (${filledCurrency}) 等于`
      // 修正数值显示:使用转换后的结果而非输入值
      after.textContent = `${convertedValue} ${currencyData[wantedCurrency]} (${wantedCurrency})`
    })
}

// 禁止输入空格
input.addEventListener('keypress', function(e) {
  if (e.keyCode === 32) {
    e.preventDefault();
  }
});

关键修改说明

  • 新增currencyData全局变量,持久化存储API返回的「货币缩写→全称」映射关系。
  • 下拉选项中添加全称展示,优化用户选择体验。
  • 修正转换结果的数值错误,改为显示实际转换后的金额。
  • 在结果文本中通过currencyData[货币缩写]获取对应全称,替换原有的缩写展示。

界面截图

内容的提问来源于stack exchange,提问作者naneli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:35:36