我有一個包含 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);
});
});
uj5u.com熱心網友回復:
您應該使用 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371779.html
標籤:javascript html 数组 foreach 附加
上一篇:基于現有的3-D陣列numpy計算沒有回圈的3-D陣列numpy值
下一篇:將ajax回應附加到html表
