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>
效果图
样式比较丑,不要介意哈