我需要动态构造以下 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 添加到表中,但无法按照上述结构进行添加,并且数组大小也不固定(可以是任意数量的元素)
这是我的 fiddle
能否请您告诉我如何添加,因为每个 tr 只能包含 4 个元素
最佳答案
您只需检查索引
,确保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>
预览
关于jquery - 如何根据给定的结构构建 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855782/