如何通过API中的Javascript数组将元素列表显示为HTML中的列表? [英] How to display a list of element in as a list in HTML from a Javascript array from an API?
本文介绍了如何通过API中的Javascript数组将元素列表显示为HTML中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的JS代码是这个,但是我希望能够将 moves
数组以列表格式显示在HTML中,我该怎么做?
My JS code is this but I want to be able to get the moves
array to be displayed in HTML in a list format, how can I go about doing so?
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>
,以便您的代码可以执行以下操作:
You can use a safe helper to populate a node in the page, let's say <div id="list"></div>
, so that your code can do something like:
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
时,这也将做正确的事.
That will also do the right thing next time you call getData
in case data changes.
这篇关于如何通过API中的Javascript数组将元素列表显示为HTML中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文