首页 > 解决方案 > 如何从 API 的 Javascript 数组中将元素列表显示为 HTML 中的列表?

问题描述

我的 JS 代码是这样的,但我希望能够让moves数组以列表格式显示在 HTML 中,我该怎么做呢?

const getData = () => {
  axios
    .get(" https://pokeapi.co/api/v2/pokemon/charmander")
    .then((response) => {
      const stats = response.data.moves;
      const moves = stats.map((obj) => {
        return obj.move.name;
      });
    })
    .catch((error) => console.log(error));
};

标签: javascripthtmlaxios

解决方案


您可以使用安全助手来填充页面中的节点,比如说<div id="list"></div>,以便您的代码可以执行以下操作:

import {render, html} from '//unpkg.com/uhtml?module';

const getData = () => {
  axios
    .get(" https://pokeapi.co/api/v2/pokemon/charmander")
    .then((response) => {
      const stats = response.data.moves;
      render(document.getElementById('list'), html`
        <ul>
          ${stats.map((obj) => html`<li>${obj.move.name}</li>`)}
        </ul>
      `);
    })
    .catch((error) => console.log(error));
};

这也将在您下次调用getData 以防数据更改时做正确的事情。


推荐阅读