首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >javascript循环每4个元素创建一行

javascript循环每4个元素创建一行
EN

Stack Overflow用户
提问于 2022-08-12 13:08:48
回答 2查看 110关注 0票数 -1

我不能履行我的职责,有人能帮我吗,谢谢。我有一个包含大量条目的json文件,我在js中创建了html。我想每4个元素创建一行。很抱歉我不能很好地格式化我的代码

代码语言:javascript
复制
function createUserList(usersList) {

  usersList.forEach(user => {

    const listItem = document.createElement("div");
    listItem.setAttribute("class", "row");
    listItem.innerHTML = `
        <div class="col-12 col-md-4 col-lg-3 isotope-item">
            <a class="img-thumbnail-variant-3" href="single-portfolio.html">
                          <div class="adaptHaut">
                              <span class="adaptTitle">
                                <span class="vertBts type">${user.type}</span><span style="color: #92C13B;">${user.nom}</span>
                              </span>
                            <figure class="adaptImg">
                              <img src="images/${user.image}" alt="" width="418" height="315"/>
                            </figure>
                          </div>
                          <div class="caption adaptHover">
                            <p class="heading-5 hover-top-element adaptDescription">Compétences scientifiques,intérêt pour les technologies de laboratoire.</p>
                            <div class="divider"></div>
                            <p class="small hover-bottom-element adaptSecondDescription">Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p>
                            <span class="icon arrow-right linear-icon-plus"></span>
                          </div>
                        </a>
                      </div>`

    searchResult.appendChild(listItem);

  })
}


{

  "results": [{
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    },
    {
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    }
  ]
}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-08-12 13:53:58

下面是将4个div连接到一行并在行之间插入一个<hr>的尝试。每次循环索引的表达式i&&!(i%4)true时,都会在当前元素之前插入一个<hr>元素。

代码语言:javascript
复制
function createUserList(usersList) {

  document.getElementById("searchresult").innerHTML=usersList.map((user,i) =>`${i&&!(i%4)?"<hr>":""}
<div class="col-12 col-md-4 col-lg-3 isotope-item">
 <a class="img-thumbnail-variant-3" href="single-portfolio.html">
  <div class="adaptHaut">
   <span class="adaptTitle">
    <span class="vertBts type">${user.type}</span>
    <span style="color: #92C13B;">${user.nom}</span>
   </span>
   <figure class="adaptImg">
    <img src="images/${user.image}" alt="" width="41.8" height="31.5"/>
   </figure>
  </div>
  <div class="caption adaptHover">
   <p class="heading-5 hover-top-element adaptDescription">Compétences scientifiques,intérêt pour les technologies de laboratoire.</p>
   <div class="divider"></div>
   <p class="small hover-bottom-element adaptSecondDescription">Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p>
   <span class="icon arrow-right linear-icon-plus"></span>
  </div>
 </a>
</div>`).join("")
}


const usrs= {

  "results": [{
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    },
    {
      "nom": "Analyse Biologie Médical",
      "image": "MBS-phot-2.jpg",
      "type": "BTS"
    },
    {

      "nom": "Diététique",
      "image": "diet.webp",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "m2ns.jpg",
      "type": "BTS"
    },
    {

      "nom": "Nutrition Santé",
      "image": "dieteticien.jpg",
      "type": "BACHELOR"
    }
  ]
}
createUserList(usrs.results)
代码语言:javascript
复制
.isotope-item {display:inline-block}
代码语言:javascript
复制
<h2>Results</h2>
<div id="searchresult"></div>

票数 1
EN

Stack Overflow用户

发布于 2022-08-12 13:28:41

不要在每次迭代中创建一个新元素,而是使用map为每个对象创建一个模板字符串,然后join将字符串数组(map返回一个新数组)放入一个HTML中。然后将该HTML分配给包含元素。

(Sidenote:如果您的数据是表格,您可能应该使用一个表。)

下面是一个简化的示例,向您展示map/join是如何协同工作的。

代码语言:javascript
复制
const arr = [
  { name: 'Rita', nom: 18, img: 'img1' },
  { name: 'Sue', nom: 19, img: 'img2' },
  { name: 'Bob', nom: 40, img: 'img3' }
];

// Accepts the array of objects
function createHTML(arr) {

  // `map` returns a new array of HTML strings which
  // is `joined` up before that final string is returned
  // from the function
  return arr.map(obj => {
    const { name, nom, img } = obj;
    return `<div>${name} - ${nom} - ${img}</div>`;
  }).join('');
}

// Get the container and assign the result of calling the
// function with the array of objects
const container = document.querySelector('.container');
container.innerHTML = createHTML(arr);
代码语言:javascript
复制
<div class="container"></div>

补充文件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73334702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档