基于JavaScript實現(xiàn)購物車功能
更新時間:2017年02月07日 15:08:43 作者:醬果子
這篇文章主要為大家詳細介紹了基于JavaScript實現(xiàn)購物車功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js實現(xiàn)購物車功能的具體代碼,供大家參考,具體內(nèi)容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-1.12.4.js"></script> </head> <body> <div id="shop"> <button id="btAdd">我的購物車</button><br><br> <table id="cart"> <thead> <tr> <th>單價</th> <th>數(shù)量</th> <th>小計</th> <th>操作</th> </tr> </thead> <tbody> </tbody> <tfoot> <tr> <td colspan="4">購物車總金額:<span id="total">0.00</span></td> </tr> </tfoot> </table> </div> <div id="footer"></div> <script> $('#read .page li a').click(function(){ var n=$(this).html(); $(this).parent().parent().next().children('p:nth-child('+n+')').slideDown(2000); $(this).parent().parent().next().children('p:nth-child('+n+')').siblings().css('display','none'); }) $('#btAdd').click(function(){ var p = randPrice(); var c = randCount(); $('#cart tbody').append('<tr>'+ '<td>'+p+'</td>'+ '<td><input type="text" value="'+c+'"></td>'+ '<td>'+parseFloat((p*c).toFixed(2))+'</td>'+ '<td><a href="#" rel="external nofollow" >×</a></td>'+ '</tr>'); $('#total').html( getTotal() ); }); //為“刪除”按鈕(即X號)綁定事件監(jiān)聽函數(shù),注意:X是后添加的,很多X執(zhí)行的行為是一樣的——使用事件代理 $('#cart tbody').delegate('td > a', 'click',function(event){ event.preventDefault(); var a = event.target; $(a).parent().parent().remove(); }); //為“購買數(shù)量”輸入框做事件綁定——使用事件代理 $('#cart tbody').delegate('td > input','change', function(event){ var input = event.target; var count = input.value; var price = $(input).parent().prev().html(); $(input).parent().next().html( price*count ); $('#total').html( getTotal() ); }) //計算購物車的總金額 function getTotal(){ var sum = 0; $('#cart tbody tr td:nth-child(3)').each(function(i, td){ sum += parseInt(td.innerHTML); }) return sum; } function randPrice(){ var p = Math.random()*100; p = p.toFixed(2); p = parseFloat(p); return p; } function randCount() { var c = Math.floor(Math.random() * 10 + 1); return c; } $('#header').load('php/header.php'); $('#footer').load('php/footer.php'); var theme=localStorage.getItem('ChoseTheme'); applyTheme(theme) </script> </body> </html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript fullscreen全屏實現(xiàn)代碼
用了實現(xiàn)打開一個滿屏的代碼2009-04-04Three.js后期處理效果(發(fā)光描邊OutlinePass)
這篇文章主要給大家介紹了關(guān)于Three.js后期處理效果(發(fā)光描邊OutlinePass)的相關(guān)資料,Three js 開發(fā)的一些知識整理,方便后期遇到類似的問題,能夠及時查閱使用,需要的朋友可以參考下2024-01-01javascript中傳統(tǒng)事件與現(xiàn)代事件
本文給大家介紹的是使用傳統(tǒng)事件的方法來模擬現(xiàn)代事件,十分的簡單實用,有需要的小伙伴可以參考下。2015-06-06