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

调用fetch API获取数据后无法将带选项的select元素添加到DOM

代码问题修复说明

存在的错误点

  • fetch响应处理阶段调用json方法未加执行括号,response.json需修改为response.json()
  • 创建DOM元素时未挂载到document对象,直接调用createElement无效,需修改为document.createElement()
  • 选项内容拼接使用了错误的语法,JS模板字符串需用反引号包裹,变量占位符格式为${变量名}
  • 可选优化:恢复option的value属性设置,方便后续业务逻辑获取选中的货币编码

修正后可运行代码

const btn = document.createElement("button");
btn.setAttribute("id", "getCurrencies");
btn.innerHTML = "Click me!";
document.body.appendChild(btn);

btn.addEventListener("click", (e) => {
  fetch("https://api.frankfurter.app/latest")
    .then((response) => response.json())
    .then((data) => {
      const selectEL = document.createElement("select");
      Object.entries(data.rates).forEach(([code, value]) => {
        const optionEl = document.createElement("option");
        optionEl.setAttribute("value", code);
        optionEl.innerHTML = `${code} : ${value}`;
        selectEL.appendChild(optionEl);
      });
      document.body.appendChild(selectEL);
    })
    .catch((err) => console.log(err));
});

修正后点击按钮即可正常发起接口请求,将返回的汇率数据渲染为下拉框的对应选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:06:03