基于JavaScript實(shí)現(xiàn)購物車功能
更新時間:2017年02月07日 15:08:43 作者:醬果子
這篇文章主要為大家詳細(xì)介紹了基于JavaScript實(shí)現(xiàn)購物車功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了js實(shí)現(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中return返回多個值的三個方法實(shí)現(xiàn)
本文主要介紹了JavaScript中return返回多個值的三個方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
BootstrapValidator超詳細(xì)教程(推薦)
這篇文章主要介紹了BootstrapValidator超詳細(xì)教程(推薦)的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12
使用uniapp打包微信小程序時主包和vendor.js過大解決(uniCloud的插件分包)
每個使用分包小程序必定含有一個主包,所謂的主包,即放置默認(rèn)啟動頁面/TabBar頁面,以及一些所有分包都需用到公共資源/JS 腳本,下面這篇文章主要給大家介紹了關(guān)于使用uniapp打包微信小程序時主包和vendor.js過大解決的相關(guān)資料,,需要的朋友可以參考下2023-02-02
如何解決java.lang.NumberFormatException: null異常
這篇文章主要介紹了如何解決java.lang.NumberFormatException: null異常問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

