日期:2014-05-16  浏览次数:20462 次

(原创)实例讲解JS复选框动态计算表格每列总和

?

?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>无标题文档</title>

<SCRIPT LANGUAGE="JavaScript">

<!--

?

function countNum(e) {

var tab=document.getElementById("abc");

var obj=e.parentNode.parentNode; ?

var id=parseInt(obj.rowIndex)-1;?

var checkbox=document.getElementsByName("checkbox");

var sumStr01 = 0;

var sumStr02 = 0;

var sumStr03 = 0;

var sumStr04 = 0;

for(var j=0;j <checkbox.length;j++) ?

{ ?

if(document.getElementsByName("checkbox")[j].checked){

var num = parseInt(tab.rows[j+1].cells[1].innerText);

sumStr01 = parseInt(sumStr01) + num;

?

var num = parseInt(tab.rows[j+1].cells[2].innerText);

sumStr02 = parseInt(sumStr02) + num;?

?

var num = parseInt(tab.rows[j+1].cells[3].innerText);

sumStr03 = parseInt(sumStr03) + num;?

?

var num = parseInt(tab.rows[j+1].cells[4].innerText);

sumStr04 = parseInt(sumStr04) + num;?

//alert(tab.rows[j+1].cells[1].innerText);

}

} ?

sum01.innerHTML =sumStr01;?

sum02.innerHTML =sumStr02;?

sum03.innerHTML =sumStr03;?

sum04.innerHTML =sumStr04;?

}

//-->

</SCRIPT>

</head>

?

<body>

<table id="abc" width="1000" border="1" cellspacing="10" cellpadding="10">

??<tr>

?? ?<th scope="col">操作</th>

?? ?<th scope="col">A</th>

?? ?<th scope="col">B</th>

?? ?<th scope="col">C</th>

?? ?<th scope="col">D</th>

??</tr>

??<tr>

?? ?<td><div align="center"> ? ? ?

?? ? ? ?<input type="checkbox" name="checkbox" value="checkbox" onclick='countNum(this);'/>

?? ? ?</div></td>

?? ?<td><div align="center" name="amount">1</div></td>

?? ?<td><div align="center" name="amount">5</div></td>

?? ?<td><div align="center" name="amount">3</div></td>

?? ?<td><div align="center">41</div></td>

??</tr>

??<tr>

?? ?<td><div align="center">

?? ? ?<input type="checkbox" name="checkbox" value="checkbox" onclick='countNum(this);'/>

?? ?</div></td>