javascript - 如何从 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));
};
解决方案
您可以使用安全助手来填充页面中的节点,比如说<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
以防数据更改时做正确的事情。
推荐阅读
- r - 从 MCMCglmm 中提取随机效应
- javascript - 如何在同一页面上显示两个幻灯片?
- lua - 为什么在 LuaJIT 和 Lua 中格式化数字的方式不同?
- reactjs - 反应警告:道具 x 不匹配。服务器:x 客户端:x
- kubernetes - 如何从 GCP 中另一个项目的 pod 访问一个项目的 kubernets 服务
- mysql - MySQL MD5 查询
- python - 为什么我的正则表达式不匹配以下数字字符串?
- python - 按一天中的星期分组 DateTime
- java - 如何将 SMT 应用于 Kafka 连接中的单个主题?
- c# - 指定公共交通中的发布超时