前端學習程式碼例項-JavaScript商城購物車價格自動計算功能
摘要:
分享一段程式碼例項,它實現購物車價格自動計算功能。
程式碼例項如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name=...
分享一段程式碼例項,它實現購物車價格自動計算功能。
程式碼例項如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>web前端開發學習q群:731771211詳細教程講解</title> <style type="text/css"> #imgtest{ position:absolute; top:100px; left:400px; z-index:1; } table{ left:100px; font-size:20px; } </style> <script> function total(id){ /*計算單個的價格*/ var quantity=document.getElementById("quantity"+id).value; var price=document.getElementById("price"+id).value; var smallTotal=quantity*price; var smallT=document.getElementById("smallTotal"+id); smallT.innerHTML=smallTotal; /*計算總價格*/ var totalPrice=0; for(var a=1;a<3;a++){ var quantity=document.getElementById("quantity"+a).value; var price=document.getElementById("price"+a).value; var smallTotal=quantity*price; totalPrice=totalPrice+smallTotal; } var total=document.getElementById("total"); total.innerHTML=totalPrice; } function initialize(){ var totalPrice=0; for(var a=1;a<3;a++){ var quantity=document.getElementById("quantity"+a).value; var price=document.getElementById("price"+a).value; var smallTotal=quantity*price; totalPrice=totalPrice+smallTotal; var smallT=document.getElementById("smallTotal"+a); smallT.innerHTML=smallTotal; } /*取出購物車的所有商品的價格總和*/ var total=document.getElementById("total"); total.innerHTML=totalPrice; } window.onload=function(){ initialize(); } </script> </head> <body> <div id="imgtest"></div> <table border="1" style="text-align:center;" align="center"> <thead style="height:50"> <td style="width:300px">商品名稱</td> <td style="width:170px">數量</td> <td style="width:170px">價格</td> <td style="width:250px">小計</td> </thead> <tbody> <tr> <td class="name">我的帥氣一</td> <td class="quantity"><input id="quantity1" value="1"/></td> <td class="price"><input type="hidden" id="price1" value="20"/>20</td> <td class="total"><span id="smallTotal1"></span> 元</td> </tr> <tr> <td class="name">我的智慧二</td> <td class="quantity"><input id="quantity2" value="2"/></td> <td class="price"><input type="hidden" id="price2" value="30"/>30</td> <td class="total"><span id="smallTotal2"></span> 元</td> </tr> <tr> <td colspan="3" class="cart_total"></td> <td><span class="red">總計:</span><span id="total"></span>元</td> </tr> </tbody> </table> </body> </html>