如何将列拆分为行

时间:2018-08-13 04:47:41

标签: javascript jquery loops

例如:如果我的obj的数据长度为6。我们知道如果我们在表行中循环,那么我们将得到6行和1列。

现在我想用我的规则使之循环,如果设置3条规则,那么我将获得3列2行,或者如果设置6则得到6列仅1行

希望有人可以提供帮助

谢谢

<!DOCTYPE html>
<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>

<h2>JavaScript Loops</h2>

<p id="demo"></p>
<table id="tbl" border="1px">
<tr id="tbl_tr"></tr>
</table>

<script>
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
var row=$("#tbl_tr");
for (i = 0; i < cars.length; i++) {
    text +="<tr>";
    text += "<td>"+cars[i] + "</td>";
    text +="</tr>";
}
row.html(text);
//document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

为了实现您要执行的操作,您需要实现一个易于实现的拆分器逻辑。如果达到特定点,则必须传递一行中应该包含多少个单元格。

检查以下代码段:

var tblspliter = $('#tblspliter');
var spliterCell = $('#txtspliter');
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

$('#btnsplit').on('click', function() {

  if (spliterCell.val() !== '') {
    tblspliter.empty(); //refreshing the table  
    let tbody = $('<tbody></tbody>');
    let tr = $('<tr></tr>');
    let appendedRow = 0;
    for (let i = 0; i < cars.length; i++) {
      if (spliterCell.val() == appendedRow) {
        tbody.append(tr);
        tr = $('<tr></tr>');
        appendedRow = 0;
      }
      tr.append('<td>' + cars[i] + '</td>');
      appendedRow++;
    }
    tbody.append(tr);
    tblspliter.append(tbody);
  } else
    alert('unable to split enter value');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="txtspliter">Splitter Cell:</label>
  <input type="number" id="txtspliter">
  <input type="button" value="split" id="btnsplit">
</div>

<table id="tblspliter" border=1>

</table>

答案 1 :(得分:0)

只需更改循环的内容即可。

for (i = 0; i < cars.length; i++) {
    if (i % 3 == 0) { // add tr at the start of the row
        text +="<tr>";
    }
    text += "<td>"+cars[i] + "</td>";
    if (i % 3 == 2) { // close tr at the end of the row. 2 is the biggest remainder when divide by 3
        text +="</tr>";
    }
}

我使用模3来获得3列,如您所述。