2016-03-14 30 views
-1

我要让2列我知道的结构是这样的自举加.row使用循环

.row 
    .col-md-6 
    .col-md-6 
.row 
    .col-md-6 
    .col-md-6 

,但如何将它使用JavaScript中循环写?

- each obj,index in obj 
     if (index > 0) 
      .row 
       .col-md-6 
+1

添加for循环为“col-md-6”创建2列或者您想要别的东西? –

+0

为什么要添加一个新的'.row'?行数大于12个col单元的行将简单地[换行到新行](http://getbootstrap.com/css/#grid-example-wrapping)。 – ZimSystem

+0

你在使用翡翠还是什么?这是不正确的Javascript语法 – kartsims

回答

0

这看起来很直截了当。你必须创建一个nested for-loop,它创建x divs,rowy div类col-md-6

var x = 2, 
    y = 2, 
    colClass = 'col-md-6', 
    rowClass = 'row', 
    rows = [], 
    i, j, currentRow, currentCol; 

// Variable x is the amount of rows to create. 
for (i = 0; i < x; i++) { 

    // Create the row. 
    currentRow = document.createElement('div'); 
    currentRow.classList.add(rowClass); 

    // Variable y is the amount of columns to create for each row. 
    for (j = 0; j < y; j++) { 

     // Create the column. 
     currentCol = document.createElement('div'); 
     currentCol.classList.add(colClass); 

     // Append the column to the row. 
     currentRow.appendChild(currentCol); 
    } 

    // Add the row to an array of rows. 
    rows.push(currentRow); 
} 

// Append the rows to something, or do something else with them. 
// Below practice could already be done inside the for loop, instead of rows.push(currentRow) 
rows.forEach(function (row) { 
    document.body.appendChild(row); 
});