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;
}
嘿,我试图为数组的第一个对象添加一个图像,但它出现在图像的两个对象上。所以任何建议
中的回调函数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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句