【问题标题】:I want to put the contents of arrays into h3 element then put it into their its containers我想将数组的内容放入 h3 元素中,然后将其放入其容器中
【发布时间】: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);
          });
          
        });

【问题讨论】:

    标签: javascript html arrays foreach append


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 2017-12-13
      • 2020-06-16
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多