gpt4 book ai didi

javascript - 如何在一行中显示数组列表中的一定数量的项目

转载 作者:行者123 更新时间:2023-12-02 21:31:39 30 4
gpt4 key购买 nike

我正在使用 drivers2020.forEach(addLink); 显示列表中的所有项目。
它们都显示在一行中,有没有办法设置一些项目,这些项目将显示在一行中,当达到该数量时,开始一个新的?

这是我的函数的样子:

drivers2020.forEach(addLink);

function addLink(driver, i) {
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.style.width = "250px";
wrapper.style.float = "left";
const nameList = document.createElement('h2');
nameList.id = `listOfNames`;
nameList.textContent = driver.name;
const driverImg = document.createElement('img');
driverImg.src = driver.image;
wrapper.appendChild(driverImg);
wrapper.appendChild(nameList);
list2020.appendChild(wrapper);
nameList.addEventListener('click', function () {
driverProfile(driver, this)
});
}

最佳答案

使用现有代码执行此操作的最简单方法是使用 CSS Grid :

#list2020 {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}

您可以通过在此处操作此行来调整列数:

网格模板列:重复(3, 1fr);

const drivers2020 = [
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
},
{
name: 'Name',
image: 'https://via.placeholder.com/150'
}
];
const list2020 = document.getElementById('list2020');
drivers2020.forEach(addLink);

function addLink(driver, i) {
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.style.width = "250px";
wrapper.style.float = "left";
const nameList = document.createElement('h2');
nameList.id = `listOfNames`;
nameList.textContent = driver.name;
const driverImg = document.createElement('img');
driverImg.src = driver.image;
wrapper.appendChild(driverImg);
wrapper.appendChild(nameList);
list2020.appendChild(wrapper);
nameList.addEventListener('click', function() {
driverProfile(driver, this)
});
}
#list2020 {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}
<div id="list2020"></div>

关于javascript - 如何在一行中显示数组列表中的一定数量的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60609412/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com