JS实现购物车01

Posted Foryourfuture

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS实现购物车01相关的知识,希望对你有一定的参考价值。

需求

使用JS实现购物车功能01

具体代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车01</title>
<style type="text/css">
.num{
width:20px;
}


</style>
</head>
<body>
<table align="center" border="2" id = "cart">
<tr>
<td colspan="5" align="center"><input id="add" type="button" value="添加"></td>
</tr>
<tr>
<td>商品名称</td>
<td>单价</td>
<td>数量</td>
<td>小计</td>
<td>操作</td>
</tr>
</table>

<script type="text/javascript">
document.getElementById("add").onclick = function(){
var goods_name = prompt("请输入商品名称");
if(goods_name==null){
alert("放弃添加");
return;
}
var goods_price = prompt("请输入商品单价");

if(goods_price==null){
alert("放弃添加");
return;
}
if(isNaN(goods_price)){
alert("单价格式不正确");
return;
}


var table = document.getElementById("cart");


var row = table.insertRow();
var col1=row.insertCell();
col1.innerHTML = goods_name;


var col2=row.insertCell();
col2.innerHTML = "¥" + goods_price;


var col3=row.insertCell();
col3.innerHTML = \'<input type="button" value="-" onclick = "changNum(this);"><input type="text" class="num" value="1"><input type="button" value="+" onclick = "changNum(this);">\';


var col4=row.insertCell();
col4.innerHTML = "¥" + goods_price;


var col5=row.insertCell();
col5.innerHTML = "<button onclick=\'removeRow(this);\'>删除</button>";


}


function removeRow(btn){
var row = btn.parentNode.parentNode;
var index = row.rowIndex;
var table = document.getElementById("cart");
table.deleteRow(index);
}


function changNum(btn){


if(btn.value == "-"){
var count = btn.nextSibling;
//是否数量为1
if(count.value == 1){
alert("数量不能继续减少了");
return;
}
count.value = parseInt(count.value) - 1;


//找到单价
var price = btn.parentNode.previousSibling.innerHTML.substring(1);//字符串截取
//改变小计
var SubTotal = count.value * price;
//填入小计
btn.parentNode.nextSibling.innerHTML = "¥" + SubTotal;


}else if(btn.value == "+"){
//控制文本框中的数量
btn.previousSibling.value = parseInt(btn.previousSibling.value) + 1;
//找到单价
var price = btn.parentNode.previousSibling.innerHTML.substring(1);//字符串截取
//改变小计
var SubTotal = btn.previousSibling.value * price;
//填入小计
btn.parentNode.nextSibling.innerHTML = "¥" + SubTotal;
}
}


</script>
</body>
</html>

效果图
样式比较丑,不要介意哈

 

以上是关于JS实现购物车01的主要内容,如果未能解决你的问题,请参考以下文章

JS代码实现商品价钱总和(模拟购物车功能)

记录-JS简单实现购物车图片局部放大预览效果

每日一题_JavaScript.利用Js操作frameset框架集对象实现购物车?

angularJS使用ocLazyLoad实现js延迟加载

js实现的购物车选中商品实现计算商品总价格

Redux案例实现购物车