我想将数组的内容放入 h3 元素中,然后将其放入其容器中
Posted
技术标签:
【中文标题】我想将数组的内容放入 h3 元素中,然后将其放入其容器中【英文标题】:I want to put the contents of arrays into h3 element then put it into their its containers 【发布时间】:2022-01-08 22:48:28 【问题描述】:我有一个包含 10 个数组的数组,并将一个数组放入它的每个容器中,创建一个包含该数组内容的 h3。但是发生的事情是所有数组都进入了它们的所有容器。 你可以看下面的例子
.list-container
width: 300px;
background: royalblue;
padding: 1em;
margin: 2rem;
h3
display: inline-block;
font-size: .75rem;
color: white;
padding: .75em;
background: red;
margin: .75rem;
/* this is exempla style */
.example
width: 300px;
background: royalblue;
padding: 1em;
margin: 2rem;
<div class="list-container">
</div>
<div class="list-container">
</div>
<!-- this are the examples -->
<h2>below is the correct example</h2>
<div class="example">
<h3>Frontend</h3>
<h3>Senior</h3>
<h3>html</h3>
<h3>CSS</h3>
<h3>javascript</h3>
</div>
<div class="example">
<h3>Fullstack</h3>
<h3>Midweight</h3>
<h3>Python</h3>
<h3>React</h3>
</div>
const arrList = [
["Frontend", "Senior", "HTML", "CSS", "JavaScript"],
["Fullstack", "Midweight", "Python", "React"]
];
const listContainer = document.querySelectorAll('.list-container');
listContainer.forEach(container =>
arrList.forEach(list =>
const h3 = document.createElement('h3');
h3.innerHTML = list;
container.append(h3);
);
);
【问题讨论】:
【参考方案1】:您应该使用 forEach 函数的 index 参数,根据容器索引选择要使用的数组内容:
const arrList = [
["Frontend", "Senior", "HTML", "CSS", "JavaScript"],
["Fullstack", "Midweight", "Python", "React"]
];
const listContainer = document.querySelectorAll('.list-container');
listContainer.forEach((container, index) =>
arrList[index].forEach(list =>
const h3 = document.createElement('h3');
h3.innerHTML = list;
container.append(h3);
);
);
.list-container
width: 300px;
background: royalblue;
padding: 1em;
margin: 2rem;
h3
display: inline-block;
font-size: .75rem;
color: white;
padding: .75em;
background: red;
margin: .75rem;
/* this is exempla style */
.example
width: 300px;
background: royalblue;
padding: 1em;
margin: 2rem;
<div class="list-container">
</div>
<div class="list-container">
</div>
【讨论】:
以上是关于我想将数组的内容放入 h3 元素中,然后将其放入其容器中的主要内容,如果未能解决你的问题,请参考以下文章