javascript forEach 循环创建一个新元素

问题描述

当我的 forEach 循环读取数组的任何索引时,我想在 javascript 中创建一个新的 img 元素,这是代码

axios.get('https://jsonplaceholder.typicode.com/photos',{params: {_limit: 20}}).then(res => {
  let values = Object.values(res);
  values[0].forEach((item) => {
    document.getElementById('root').innerHTML = `<img src="${item.url}">`;
  }
})

enter image description here

解决方法

我想我会根据 Alien 先生(现已删除)的回答做一个可运行的版本。但是,正如 Vektor 的评论所指出的那样,如果您在使用 React 之类的东西,这可能没有帮助(或至少不理想)。

如果你正在使用 React 之类的东西,你更可能想要为图像数组设置状态,基于这个数组渲染图像并设置类似 useEffect 钩子/componentDidMount 方法的东西来加载图像和更新状态。

基于外星人先生(现已删除)回答的可运行版本:

const ele_with_attributes = (tag,attributes = {}) => 
  Object.assign(document.createElement(tag),attributes);

const append_image_from_api = (item) =>
  document.getElementById('images').appendChild(
    ele_with_attributes('img',{
      src: item.thumbnailUrl,//item.url,alt: item.title
    })
  );

axios
  .get('https://jsonplaceholder.typicode.com/photos',{params: {_limit: 5}})
  .then(res => res?.data?.forEach(append_image_from_api));
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<div id="images"></div>