问题描述
我正在尝试在表格中使用一行复选框,并且对于表格中的每个TD,它需要检查复选框是否被勾选,因此它是1,否则是0。 我需要一个for循环,在该循环中,我将可以循环遍历每个td,确定是否检查了它,如果是,则在二进制字符串中添加1或在二进制字符串中添加0。
这应该以每个tr结尾(从复选框中打勾或未打勾)具有自己唯一的二进制字符串。我还将要为每个tr设置自己的唯一ID。
下面的代码是我到目前为止所拥有的,但假定我走错了方向。
任何帮助表示赞赏。谢谢
[ { ID: 000,binary: 0101010101 } ]
function generate(){
$("#actionTable>tbody").children("tr").each(function(i,rowitem){
$(rowitem).children("td").each(function(index,item){
if (index == 0){
var amid = $(item).data("amid");
}
else {
//Handle checkbox
var checked = $(item.firstChild).prop('checked')
}
});
});
}
解决方法
您可以为此使用嵌套map()。外部地图会迭代行
内部映射会迭代每个输入的checked
属性,该属性先转换为数字,然后转换为字符串,然后将数组连接为最终字符串。
我不知道html是什么样子,所以现在才使用每行的行索引
const res = $('tr').map((i,el) => {
const binary = $(el).find(':checkbox').map((_,inp) => {
return `${+inp.checked}`;
}).get().join('');
return { index: i,binary};
}).get()
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox"></td>
<td><input type="checkbox" checked></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td><input type="checkbox" checked></td>
<td><input type="checkbox"></td>
<td><input type="checkbox" checked></td>
<td><input type="checkbox"></td>
</tr>
</table>