基于JavaScript实现购物车功能
更新时间:2017年02月07日 15:08:43 作者:酱果子
这篇文章主要为大家详细介绍了基于JavaScript实现购物车功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了js实现购物车功能的具体代码,供大家参考,具体内容如下
<!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>数量</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号)绑定事件监听函数,注意:X是后添加的,很多X执行的行为是一样的——使用事件代理
$('#cart tbody').delegate('td > a', 'click',function(event){
event.preventDefault();
var a = event.target;
$(a).parent().parent().remove();
});
//为“购买数量”输入框做事件绑定——使用事件代理
$('#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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
使用uniapp打包微信小程序时主包和vendor.js过大解决(uniCloud的插件分包)
每个使用分包小程序必定含有一个主包,所谓的主包,即放置默认启动页面/TabBar页面,以及一些所有分包都需用到公共资源/JS 脚本,下面这篇文章主要给大家介绍了关于使用uniapp打包微信小程序时主包和vendor.js过大解决的相关资料,,需要的朋友可以参考下2023-02-02
如何解决java.lang.NumberFormatException: null异常
这篇文章主要介绍了如何解决java.lang.NumberFormatException: null异常问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-03-03


最新评论