我需要动态构建以下HTML
<tr>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">A<span></span></label></td>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">B<span></span></label></td>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">C<span></span></label></td>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">D<span></span></label></td>
</tr>
<tr>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass" >E<span></span></label></td>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">F<span></span></label></td>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass" >G<span></span></label></td>
<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">H<span></span></label></td>
</tr>
正如您所看到的,每个tr应仅包含 4列
这是我的代码
var myarray = ["A", "B","C","D","E","F","G","H"]
$(document).ready(function()
{
var html = ''
for (var i = 0; i < myarray.length; i++)
{
html += '<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">' + myarray[i] + '<span></span></label></td>'
}
$("#mytable tbody").append(html);
});
正如您从代码中看到的那样,我只是将td&t添加到表中,但是根据上述结构无法实现,并且数组大小也没有固定(可以是任何元素数量)
这是我的小提琴
请您告诉我如何添加,因为每个tr只应包含4个元素
答案 0 :(得分:2)
您只需查看index
,确保4
的剩余部分为0
(其中4
为i + 1
获取的自然索引):
var myarray = ["A", "B", "C", "D", "E", "F", "G", "H"]
$(document).ready(function() {
var html = ''
for (var i = 0; i < myarray.length; i++) {
html += '<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">' + myarray[i] + '<span></span></label></td>';
if ((i + 1) % 4 == 0)
html += '</tr><tr>';
}
$("#mytable tbody").append('<tr>' + html + '</tr>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="mytable">
<tbody>
</tbody>
</table>
预览强>
答案 1 :(得分:1)
另一种方式
var myarray = ["A", "B","C","D","E","F","G","H"]
$(document).ready(function()
{
var html = ''
for (var i = 0; i < myarray.length;)
{
html+="<tr>";
for(var j=4; j>=1; j--){
html += '<td><label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" class="chkclass">' + myarray[i++] + '<span></span></label></td>';
}
html+="</tr>";
$("#mytable tbody").append(html);
html='';
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="mytable">
<tbody>
</tbody>
</table>
&#13;