【问题标题】:javascript forEach loop create a new Element [duplicate]javascript forEach循环创建一个新元素[重复]
【发布时间】:2021-02-04 21:24:11
【问题描述】:

当我的 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}">`;
  }
})

【问题讨论】:

  • 请不要链接到您在第三方网站上的代码,因为链接会随着时间的推移而失效,请不要分享您的代码图片,分享代码本身的文本,就在您的问题中.
  • 您需要将完整的代码作为文本共享,对于ButtonApp 组件,最好是作为sn-p,因为有很多方法可以解决这个问题。

标签: javascript html foreach axios


【解决方案1】:

我想我会根据 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多