當選擇修改資料後將自動計算每一個物品的的總價,並重新計算所有物品的總價.
因為沒有做太多相容性的東西,所以只在firefox下測試過.
DOM
<div>
<table id="PriceTable">
<thead><tr><td>物品編號</td><td>物品名稱</td><td >數量</td><td>價格</td><td>小計</td></tr></thead>
<tbody>
<tr><td >jsp_123</td><td >電腦</td><td><input type="text" value="1" /></td><td >1950</td><td >1950</td></tr>
<tr><td >jsp_123</td><td >電腦</td><td><input type="text" value="1" /></td><td >1950</td><td>1950</td></tr>
<tr><td >jsp_123</td><td >電腦</td><td><input type="text" value="1" /></td><td >1950</td><td >1950</td></tr>
<tr><td>jsp_123</td><td>電腦</td><td><input type="text" value="1" /></td><td>1950</td><td>1950</td></tr>
</tbody>
<tfoot>
<tr><td>總計:</td><td colspan="4">7800</td></tr>
</tfoot>
</table>
</div>
<input type="button" onclick="GetInAll()" value="計算" />
JS:
<title>購物車自動計價</title>
<script type="text/javascript" src="misc/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("table input").blur(function(oEven){
var num=oEven.target.parentNode.parentNode.cells[2].firstChild.value;
var price=oEven.target.parentNode.parentNode.cells[3].textContent;
var count=parseFloat(num)*parseFloat(price);//計算單個物品價格
oEven.target.parentNode.parentNode.cells[4].textContent=count;
GetInAll();//計算所有物品價格
});
})
function GetInAll()
{
var table=document.getElementById("PriceTable");
var oBody=table.tBodies[0];
var oFoot=table.tFoot;
var rows=oBody.rows;
var priceCount=0;
for(var i=0;i<rows.length;i++)
{
var tempData=rows[i].cells[4].textContent;
priceCount=parseFloat(priceCount)+parseFloat(tempData);
}
alert(priceCount);
oFoot.rows[0].cells[1].textContent=priceCount;
}
</script>
<style type="text/css">
table input[type=text]{ width:32px;}
</style>