最终效果:
代码如下
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>多选框的各种操作</title>
<style type="text/css">
.box{margin:50px auto;width:500px;}
input{width:30px;height:30px;display:inline-block;}
.box2 div.on{background:red;}
</style>
</head>
<body>
<div class="box">
<div class="box1">
<input type="checkbox" name="001" id="001" value="" />
<input type="checkbox" name="002" id="002" value="" />
<input type="checkbox" name="003" id="003" value="" />
<input type="checkbox" name="004" id="004" value="" />
<input type="checkbox" name="005" id="005" value="" />
<a class="box1-btn" href="javascript:;">获取</a>
</div>
<div class="box2">
<div>
<input type="checkbox" name="006" id="006" value="" />
</div>
<div>
<input type="checkbox" name="007" id="007" value="" />
</div>
<div>
<input type="checkbox" name="008" id="008" value="" />
</div>
<div>
<input type="checkbox" name="009" id="009" value="" />
</div>
<div>
<input type="checkbox" name="010" id="010" value="" />
</div>
</div>
</div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
//获取所选中元素的id-S
$('.box1-btn').click(function(){
var result_1 = '';
$('.box1 input').each(function(){
if($(this).is(':checked')){
result_1+=$(this).attr('id')+','
console.log(result_1)
}
});
});
//获取所选中元素的id-E
// 根据ID选中对应的元素-S
var arr = ["006","008"];
for(var i=0;i<arr.length;i++){
$('#'+arr[i]).attr('checked',true).parent('div').addClass('on');//这是jq的写法
// 下面这两个都是ES6语法(用到了es6中的新增特性:模板对象)
//$(`#${arr[i]}`).attr('checked',true).parent('div').addClass('on')
//$(`#${arr[i]}`).parent('div').addClass('on') 因为把这段集合到上面了,所以可以注释了
}
// 根据ID选中对应的元素-E
});
</script>