本文執行個體講述了javascript實現點擊商品列表checkbox即時統計金額的方法。分享給大家供大家參考。具體實現方法如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!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=utf-8" /> <title>商品列表統計金額</title> <style type="text/css"> body,div,p { margin:0; padding:0; font-size:14px; } #sumMoney { font-size:26px; font-weight:bold; color:Red; } </style> <script type="text/javascript"> //全選和全清 function checkAll() { var chkItems = document.getElementsByName("item"); for (var i = 0; i < chkItems.length; i++) { chkItems[i].checked = event.srcElement.checked; } calculateMoney(); } //統計所有選中的產品金額 function calculateMoney() { var sum = 0; var chkItems = document.getElementsByName("item"); for (var i = 0; i < chkItems.length; i++) { if (chkItems[i].checked) { sum += parseInt(chkItems[i].value); } } var sumMoneyObj = document.getElementById("sumMoney"); sumMoneyObj.innerHTML = "總金額:" + sum; } //給每個產品複選框加上自動統計功能 function iniEvent() { var chkItems = document.getElementsByName("item"); for (var i = 0; i < chkItems.length; i++) { chkItems[i].onclick = calculateMoney; } } </script> </head> <body onload="iniEvent()"> <div id="divMain"> <p><input type="checkbox" name="全選" onclick="checkAll()" />全選</p> <p><input type="checkbox" name="item" value="2999" />¥2999 Haier/海爾 KFR-35GW/03GJC12-DS</p> <p><input type="checkbox" name="item" value="2256" />¥2256 天貓年貨 AUX/奧克斯 KFR-35GW/SFA+2</p> <p><input type="checkbox" name="item" value="2799" />¥2799 Gree/格力 KFR-26G(26556)FNDe-3</p> <p><input type="checkbox" name="item" value="2008" />¥2008 AUX/奧克斯 KFR-25GW/SFA+2</p> <p><input type="checkbox" name="item" value="2598" />¥2598 Hisense/海信 KFR-35GW/EF11S3</p> <p><input type="checkbox" name="item" value="1877" />¥1877 TCL KFRd-25GW/DE22</p> <p><input type="checkbox" name="item" value="2398" />¥2398 Kelon/科龍 KFR-35GW/EFVCS3</p> <p><input type="checkbox" name="item" value="1999" />¥1999 TCL KFRd-35GW/FC23</p> <p><input type="checkbox" name="全選" onclick="checkAll()" />全選</p> <p><span id="sumMoney">總金額:</span></p> </div> </body> </html> |
希望本文所述對大家的javascript程式設計有所協助。