【问题标题】:adding image for each object in array DOM Javascript为数组 DOM Javascript 中的每个对象添加图像
【发布时间】:2021-08-10 19:16:06
【问题描述】:
const myBooks = [
  {
    title: 'Why We Sleep',
    author: 'Matthew Walker',
  },
  {
    title: 'All freinds',
    author: 'Christian'
  }
];
function createBookList(books) {
  let list = document.createElement('ul');
  books.forEach((sam) => {
    let li = document.createElement('li');
    let p = document.createElement('p');
    let image = document.createElement('img');
    image.src = 'https://media-amazon.com/7ov383lj3Rr';

    p.textContent = `${sam.title} - ${sam.author}`;
    li.style.listStyleType = 'none';
    list.appendChild(li);
    list.appendChild(p);
    list.appendChild(image);
  });
  return list;
}

嘿,我正在尝试仅为数组的第一个对象添加图像,但它同时出现在图像的两个对象中。所以任何建议

【问题讨论】:

  • idx 添加为forEach 中的第二个参数并添加if (idx === 0) {...here add img...}

标签: javascript arrays dom


【解决方案1】:

Array.prototype.forEach()中的回调函数暴露了三个值;数组中的当前项、数组的当前索引以及正在循环的数组。

使用第二个参数索引,您可以评估您在循环中的位置并为特定索引创建逻辑,例如数组0 中的第一项。

哦,我认为您的意思是将段落和图像附加到列表项,而不是列表本身。

const myBooks = [
  {
    title: 'Why We Sleep',
    author: 'Matthew Walker',
  },
  {
    title: 'All freinds',
    author: 'Christian'
  }
];

function createBookList(books) {
  let list = document.createElement('ul');

  books.forEach((wiz, index) => {
    let li = document.createElement('li');
    let p = document.createElement('p');

    p.textContent = `${wiz.title} - ${wiz.author}`;
    li.style.listStyleType = 'none';
    li.appendChild(p);

    if (index === 0) {
      let image = document.createElement('img');
      image.src = 'https://media.s-bol.com/7ov383lj3Rr/800x1200.jpg';
      li.appendChild(image);
    }

    list.appendChild(li);
  });

  return list;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2016-11-27
    • 2021-11-01
    相关资源
    最近更新 更多