標籤:js實現購物車完整功能
HTML代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="renderer" content="webkit"> <title>A03號桌</title> <link rel="stylesheet" href="resources/css/main.css"></head><body> <!--購物車--> <div class="shopCart"> <!--可以在table外面套一個div寫死寬高並設定overflow-y:scroll;,出現大量內容時,讓table縱向滾動--> <div class="cartBox"> <table class="cart"> <thead> <tr> <th>菜品名稱</th> <th>數量</th> <th>單價</th> <th>價格</th> </tr> </thead> <tbody> <tr> <td>大閘蟹</td> <td> <button class="add">+</button> <span class="count">1</span> <button class="reduce">-</button> </td> <td> ¥<span class="price">68.00</span> </td> <td> ¥<span class="sub_total">68.00</span> </td> </tr> <tr> <td>在天願作比翼鳥</td> <td> <button class="add">+</button> <span class="count">1</span> <button class="reduce">-</button> </td> <td> ¥<span class="price">68.00</span> </td> <td> ¥<span class="sub_total">68.00</span> </td> </tr> <tr> <td>紅嘴綠鸚哥</td> <td> <button class="add">+</button> <span class="count">1</span> <button class="reduce">-</button> </td> <td> ¥<span class="price">68.00</span> </td> <td> ¥<span class="sub_total">68.00</span> </td> </tr> </tbody> </table> </div> <ul class="totalInfo clearfix"> <li> <span class="total"> 合計:<i>¥</i><b>242.00</b> </span> </li> <li> <button class="btn-save">儲存</button> </li> </ul> </div><script src="resources/js/jquery-1.8.3.min.js"></script><script src="resources/js/shopCart.js"></script></body></html>
JS代碼:
/****點擊增加按鈕****/$(‘.add‘).click(function(){ //修改數量 var n=$(this).next().html(); var num=parseInt(n)+1; $(this).next().html(num); //計算價格 var c= $(this).parent().siblings().children(‘.price‘).html(); parseInt(c); var subPrice = num * c; var sub_price = subPrice.toFixed(2); //保留小數點後面兩位小數 $(this).parent().siblings().children(‘.sub_total‘).html(sub_price); //計算總價 var total=0; $(‘.sub_total‘).each(function(){ var price=parseInt($(this).html()); total+=price; var total_price = total.toFixed(2); $(‘.total b‘).html(total_price); });});/****點擊減少按鈕****/$(‘.reduce‘).click(function(){ //修改數量 var n=$(this).prev().html(); var num=parseInt(n)-1; if(num==0){return;}//數量減到0就能再減了 $(this).prev().html(num); //計算價格 var c= $(this).parent().siblings().children(‘.price‘).html(); parseInt(c); var subPrice = num * c; subPrice.toFixed(2); var sub_price = subPrice.toFixed(2); $(this).parent().siblings().children(‘.sub_total‘).html(sub_price); //計算總價 var total=0; $(‘.sub_total‘).each(function(){ var price=parseInt($(this).html()); total+=price; var total_price = total.toFixed(2); $(‘.total b‘).html(total_price); });});
考慮到篇幅問題,沒有貼出CSS代碼,最終頁面如下:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/89/1C/wKioL1gIYA6g7MTbAAEULD6Wu_A791.png" title="QQ20161020141040.png" alt="wKioL1gIYA6g7MTbAAEULD6Wu_A791.png" />
本文出自 “dapengtalk” 部落格,請務必保留此出處http://dapengtalk.blog.51cto.com/11549574/1863852
jquery實現購物車數量加減,價格計算功能