一、导语
我们在使用页面的时候,经常遇到选择多条数据或者取消多条数据,还有就是反选功能,这些是我们经常用的,我们今天就来看看怎么实现的。
二、效果图
三、checkbox获取值
checkbox对象.checked //获取值
checkbox对象.checked = true //设置值为true
示例:
四、全选和反选以及取消的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.c1{
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.6;
z-index: 9;
}
.c2{
width: 500px;
height: 400px;
background-color: white;
position: fixed;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -200px;
z-index: 10;
}
</style>
</head>
<body style="margin: 0;">
<div>
<input type="button" value="添加" οnclick="showModel();"/>
<input type="button" value="全选" οnclick="chooseAll();"/>
<input type="button" value="取消" οnclick="cancleAll();"/>
<input type="button" value="反选" οnclick="reverseAll();"/>
<table border="1">
<thead>
<tr>
<th>选择</th>
<th>主机名</th>
<th>端口</th>
</tr>
</thead>
<tbody id="tb">
<tr>
<td><input type="checkbox" id="test"/></td>
<td>192.168.1.1</td>
<td>8080</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>192.168.1.2</td>
<td>8090</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>192.168.1.2</td>
<td>8090</td>
</tr>
</tbody>
</table>
</div>
<!--遮罩层开始-->
<div id="i1" class="c1 hide"></div>
<!--遮罩层开始-->
<!--弹框层开始-->
<div id="i2" class="c2 hide">
<p><input type="text"/></p>
<p><input type="text"/></p>
<p>
<input type="button" value="取消" οnclick="hideModel()"/>
<input type="button" value="确定"/>
</p>
</div>
<!--弹框层结束-->
<script>
function showModel(){
document.getElementById("i1").classList.remove("hide");
document.getElementById("i2").classList.remove("hide");
}
function hideModel(){
document.getElementById("i1").classList.add("hide");
document.getElementById("i2").classList.add("hide");
}
function chooseAll(){ //全选
//获取所有的tr
var tbody = document.getElementById("tb");
var tr_list = tbody.children;
//循环所有的tr,current_tr
for(var i=0;i<tr_list.length;i++){
var crrent_tr = tr_list[i];
var checkbox = crrent_tr.children[0].children[0];
checkbox.checked = true
}
}
function cancleAll(){ //取消
var tbody = document.getElementById("tb");
var tr_list = tbody.children;
for(var i=0;i<tr_list.length;i++){
var crrent_tr = tr_list[i];
var checkbox = crrent_tr.children[0].children[0];
checkbox.checked = false;
}
}
//反选,应该先获取check值,如果是true,则改成false,是false改成true
function reverseAll(){
var tbody = document.getElementById("tb");
var tr_list = tbody.children;
for(var i=0;i<tr_list.length;i++){
var crrent_tr = tr_list[i];
var checkbox = crrent_tr.children[0].children[0];
//checkbox.checked = false;
if(checkbox.checked){
checkbox.checked = false;
}else{
checkbox.checked = true;
}
}
}
</script>
</body>
</html>