单击列表行前边的checkbox被选中,再单击,取消选中

需求描述:单击datatabl的一行数据,前边的checkbox被勾选上,再次点击,选中取消,第一次碰到这种需求,不过呢也很实用,简单记录一下

代码:

//html代码
<tr class="trs" >
  <td> <label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
<input type="checkbox" class="checkboxes" name="selectedIds" />
</label>
</td> <td></td> <td></td> <td></td>
</tr>

//js代码 <script type="text/javascript" th:inline="javascript" xmlns:th="http://www.w3.org/1999/xhtml"> //单击行选中checkbox 通过class选择器来控制
$('.trs').on('click' , function(){
var check = $(this).find("input[type='checkbox']");
if ($(check).is(':checked')) {
$(check).prop('checked', false);
} else {
$(check).prop('checked', true);
}
});
</script>
//js代码 另一种$('.trs').on('click' , function(){
var check = $(this).find("input[type='checkbox']");
if ($(check).is(':checked')) {
$(check).attr('checked',false).siblings().attr('checked',false);
} else {
$(check).prop('checked', true);
$('input[type=checkbox]').not($(check)).removeAttr('checked');
}
});

总结:关键就是一个class选择器,通过单击行<tr>来执行函数控制选中与否

原文地址:https://www.cnblogs.com/xuchao0506/p/9765251.html