首页 > 解决方案 > 尝试从 HTML 元素中的 api 数据格式化文本

问题描述

从天气 api 站点调用数据。让控制台记录数据以确保它确实显示出来。但似乎无法用来自 api 的数据替换 HTML 中的元素。

我对需要使用哪些函数将占位符文本替换为来自 api 的数据感到困惑。我尝试过innerHTML、textContent 和innerText。我要么用 innerHTML 未定义,要么用 textContent 什么都没有。

const api = `https://api.weather.io/v1.0/current?city=NewYork,NY&key=`;

let temperature = document.getElementById('temp');

fetch (api)
  .then(response => {
    return response.json();
  })
  .then(data => {
    console.log(data);
    temperature.innerHTML = data.temp ;
  });

api数据记录如下:

数据:0:rh 57 pod "d" lon -78.63861 pres 1007.3 timezone "America/New_York" ob_time "2019-10-28 17:40" country_code "US" cloud 0

我希望变量(温度)等于 api 数据的字符串值。

标签: javascripthtmlapi

解决方案


推荐阅读