基于JavaScript实现购物车功能
本文实例为大家分享了js实现购物车功能的具体代码,供大家参考,具体内容如下
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
<scriptsrc="js/jquery-1.12.4.js"></script>
</head>
<body>
<divid="shop">
<buttonid="btAdd">我的购物车</button><br><br>
<tableid="cart">
<thead>
<tr>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<tdcolspan="4">购物车总金额:<spanid="total">0.00</span></td>
</tr>
</tfoot>
</table>
</div>
<divid="footer"></div>
<script>
$('#read.pagelia').click(function(){
varn=$(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(){
varp=randPrice();
varc=randCount();
$('#carttbody').append('<tr>'+
'<td>'+p+'</td>'+
'<td><inputtype="text"value="'+c+'"></td>'+
'<td>'+parseFloat((p*c).toFixed(2))+'</td>'+
'<td><ahref="#"rel="externalnofollow">×</a></td>'+
'</tr>');
$('#total').html(getTotal());
});
//为“删除”按钮(即X号)绑定事件监听函数,注意:X是后添加的,很多X执行的行为是一样的——使用事件代理
$('#carttbody').delegate('td>a','click',function(event){
event.preventDefault();
vara=event.target;
$(a).parent().parent().remove();
});
//为“购买数量”输入框做事件绑定——使用事件代理
$('#carttbody').delegate('td>input','change',function(event){
varinput=event.target;
varcount=input.value;
varprice=$(input).parent().prev().html();
$(input).parent().next().html(price*count);
$('#total').html(getTotal());
})
//计算购物车的总金额
functiongetTotal(){
varsum=0;
$('#carttbodytrtd:nth-child(3)').each(function(i,td){
sum+=parseInt(td.innerHTML);
})
returnsum;
}
functionrandPrice(){
varp=Math.random()*100;
p=p.toFixed(2);
p=parseFloat(p);
returnp;
}
functionrandCount(){
varc=Math.floor(Math.random()*10+1);
returnc;
}
$('#header').load('php/header.php');
$('#footer').load('php/footer.php');
vartheme=localStorage.getItem('ChoseTheme');
applyTheme(theme)
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。