checkbox--也就是复选框,用过邮箱的应该都知道的,点击全选复选框,下面的复选框就全选了,再点的时候又都全取消了,选中一部分,点击删除将删除所选中的邮件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>checkbox.html</title>
<link rel="stylesheet" type="text/css" href="table.css">
<style type="text/css">
span:HOVER{
cursor: pointer;
}
</style>
<script type="text/javascript">
/* 全选复选框--点击时别的复选框和这个的状态一致 */
function checkAll(node){
var collCheckbox = document.getElementsByName("select");
for(x in collCheckbox){
collCheckbox[x].checked = node.checked;
}
}
/* 页面加载完毕后,为每一个checkbox添加点击事件 */
onload = function(){
addClick();
}
function addClick(){
var arrCheckbox = document.getElementsByName("select");
for(x in arrCheckbox){
arrCheckbox[x].οnclick=clickGoods;
}
}
function clickGoods(){
var arrCheckbox = document.getElementsByName("select");
var n = 0;
for(var i = 0;i < arrCheckbox.length; i++){
if(arrCheckbox[i].checked){
n++;
}
}
//indeterminate: 设置或获取用户是否已经更改了复选框的状态(不确定状态)
//checkbox有三种状态:选中、不选中、不确定
//选中或不选中时 indeterminate=false
if(arrCheckbox.length==n){
document.getElementById("checkAll").indeterminate = false;
document.getElementById("checkAll").checked = true;
}else if(n>0){
document.getElementById("checkAll").indeterminate = true;
}else{//==0
document.getElementById("checkAll").indeterminate = false;
document.getElementById("checkAll").checked = false;
}
}
function spanClick(n){
var arrCheckbox = document.getElementsByName("select");
//1、反选
if(n==2){
for(x in arrCheckbox){
arrCheckbox[x].checked = !arrCheckbox[x].checked;
}
clickGoods();
}
//2、清空和全选
if(n==0 || n==1){
for(x in arrCheckbox){
arrCheckbox[x].checked = n;
}
clickGoods();
}
}
/* 删除选中的商品 */
function deleteGoods(){
if(!confirm("您确定要删除所选商品?")){
return;
}
var arrCheckbox = document.getElementsByName("select");
for(var i = arrCheckbox.length-1; i>=0 ; i--){
if(arrCheckbox[i].checked){
/* 从arrCheckbox[i]开始往他的父节点找tr,找到后用其父节点删除自己 */
var oTrNode = arrCheckbox[i];
while(oTrNode.nodeName!="TR"){
oTrNode = oTrNode.parentNode;
}
oTrNode.parentNode.removeChild(oTrNode);
}
}
}
</script>
</head>
<body>
<table id = "tab">
<tr>
<th><input type="checkbox" οnclick="checkAll(this)" id="checkAll"></th>
<th>商品名</th>
<th>金额</th>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>吉他</td>
<td>223</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>水壶</td>
<td>123</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>炸牛奶</td>
<td>230</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>烤辣条</td>
<td>24</td>
</tr>
</table>
<br>
<span οnclick="spanClick(0)">清空</span>
<span οnclick="spanClick(1)">全选</span>
<span οnclick="spanClick(2)">反选</span>
<span οnclick="deleteGoods()">删除</span>
<!-- <span οnclick="sumMoney()">总金额</span> -->
</body>
</html>