复选框值返回并添加到字符串

问题描述

我正在尝试在表格中使用一行复选框,并且对于表格中的每个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>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...