切换选项卡时,保留复选框勾选(2)
原文: 切换选项卡时,保留复选框勾选(1)
更新内容:将选项卡显示隐藏做了封装等,考虑了更多选项卡的情况,有待更优解~~
更新后代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.top {
width: 100%;
height: 200px;
border: 1px solid #ddd;
}
.checks-outter {
margin-top: 8px;
padding-left: 10px;
}
a {
border:1px solid #ddd;
border-radius: 3px;
padding:2px 6px;
text-decoration: none;
}
</style>
</head>
<body>
<div class="top"></div>
<div class="checks-outter">
<div class="outter">
<button class="checkAll">全选</button>
<button class="checkNone">取消</button>
<div>
<a class="data" href="#tab0">数据1</a>
<a class="data" href="#tab1">数据2</a>
<a class="data" href="#tab2">数据3</a>
</div>
</div>
<div class="tabs"></div>
</div>
<script src="./js/jquery-2.2.4.min.js"></script>
<script>
var data1={name:'data1',data:['仓库1','仓库2','仓库3','仓库4','仓库5']};
var data2={name:'data2',data:['仓库1','仓库3','仓库4','仓库5','仓库7','仓库8']};
var data3={name:'data3',data:['仓库2','仓库3','仓库6']};
//把html封装,便于根据不同数据获取不同的html
function getHtml(data) {
var html="<div class='checks'>";
for(var i=0;i<data.data.length;i++) {
html+=`
<input class="item-${data.name}" type="checkbox" value="${data.data[i]}">
<span>${data.data[i]}</span>
`
}
html += "</div>";
return html;
}
var flag=0; //0-data1,1-data2,2-data3
//把选项卡中的数据渲染出来
$([getHtml(data1),getHtml(data2),getHtml(data3)].join("")).appendTo($(".tabs"));
tab(0);
//全选和取消-点击事件
$(".checkAll").on("click",function() {
var item = [".item-data1",".item-data2",".item-data3"][flag];
$(item).prop("checked",true);
})
$(".checkNone").on("click",function() {
var item = [".item-data1",".item-data2",".item-data3"][flag];
$(item).prop("checked",false);
})
//点击显示不同的数据
$(".data").on("click",function() {
flag=$(this).index();
tab(flag);
})
function tab(index){
$(".checks").hide().eq(index).show();
}
</script>
</body>
</html>