从不同行和列中的Javascript数组和Bootstrap生成动态卡HTML卡

时间:2019-06-02 09:36:42

标签: javascript html css arrays bootstrap-4

我想创建我的团队部分,其中包含多于一排且一排有5张卡片。我想创建所有团队成员的数组,并按照上述格式进行排列。但是我的问题是,当一行由5张卡片填充时,我无法使卡片在另一行中对齐。

我通过手动为3行创建3个不同的数组来做到这一点。但是我想使用单数组和单循环来做到这一点。

const teamDataOne = [
  {
    img: "img/team/man.png",
    name: "Bimal Timilsina",
    position: "Web Designer",
    facebook: "https://facebook.com/",
    email: "mailto:someone@gmail.com"
  },
  {
    img: "img/team/man.png",
    name: "Bimal Timilsina",
    position: "Web Designer",
    facebook: "https://facebook.com/",
    email: "mailto:someone@gmail.com"
  },
  {
    img: "img/team/man.png",
    name: "Bimal Timilsina",
    position: "Web Designer",
     facebook: "https://facebook.com/",
    email: "mailto:someone@gmail.com"
  },
  {
    img: "img/team/man.png",
    name: "Bimal Timilsina",
    position: "Web Designer",
     facebook: "https://facebook.com/",
    email: "mailto:someone@gmail.com"
  },
  {
    img: "img/team/man.png",
    name: "Bimal Timilsina",
    position: "Web Designer",
     facebook: "https://facebook.com/",
    email: "mailto:someone@gmail.com"
  }
];

const container = document.getElementById("teamRowOne");

teamDataOne.forEach(result => {
  // Construct card content
  const content = `
    <div class="col-md-2 shadow p-3 mb-5 bg-white rounded ">
        <img src="${result.img}" height="150" width="150" alt="name">
        <h4>${result.name}</h4>
        <h6>${result.position}</h6>
        <div class="border-bottom"></div>
        <a href="${
          result.facebook
        }" target="_blank" class="btn-social btn-facebook"><i class="fa fa-facebook"></i></a>
        <a href="${
          result.email
        }" target="_blank" class="btn-social btn-email"><i class="fa fa-envelope"></i></a>
        </div>
    `;

  // Append newyly created card element to the container
  container.innerHTML += content;
});

这是我的HTML代码:

<div class="row justify-content-around wow zoomIn" id="teamRowOne">
      </div>

我希望每行只对齐五张卡片。

2 个答案:

答案 0 :(得分:0)

当您使用引导网格类rowcol时,使用col-md-2创建列时,单行将获得6个分区,因此您可能会获得6张卡在数组中添加5个以上的团队成员后,排成一行。

由于没有将行划分为5个分区的类,但是在您的情况下,您可以添加一点空白以使其每行五张卡片。我用m-2尝试过,它的空白为2px。

将其添加到要在循环内创建列的位置

<div class="col-md-2 m-2 shadow p-3 mb-5 bg-white rounded ">

希望它对您有用。

答案 1 :(得分:0)

有上千种方法可以做到,我只想使用模运算符举例。 您可以像这样在一个循环中完成此操作:

// dont use row as a container anymore, take the parent element
var container = document.getElementById("row-container");
var content="";    
teamData.forEach(function(result,i){
  if(i == 0){
    //add start row 
    content+= '<div class="row">'
  }
  // add content
  content += '<div class="col....'

  if(i!=0 && i%5 == 0){

    // add end of row ,and start new row on every 5 elements
    content += '</div><div class="row">'
  }

});
// after looping dont forget to close the last row 
content += '</div>'
container.innerHTML += content;

(它是可调整的伪代码,可让您了解一个想法)