简体   繁体   English

在数组 DOM Javascript 中为每个 object 添加图像

[英]adding image for each object in array DOM Javascript

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;
}

Hey, I'm trying to add an image just for the first object of the array, but its appear for both object the image.嘿,我正在尝试仅为阵列的第一个 object 添加图像,但它同时出现在 object 图像中。 So any advice所以任何建议

The callback function in Array.prototype.forEach() exposes three values; Array.prototype.forEach()中的回调 function 暴露了三个值; the current item in the array, the current index of the array, and the array that is being looped over.数组中的当前项、数组的当前索引以及正在循环的数组。

With the second parameter, the index, you can assess where in the loop you are and create logic for a specific index, like the first item in the array 0 .使用第二个参数索引,您可以评估您在循环中的位置并为特定索引创建逻辑,例如数组0中的第一项。

Oh, and I think you meant to append the paragraph and the image to the list item, not the list itself.哦,我认为您的意思是将 append 段落和图像添加到列表项,而不是列表本身。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM