需求javascript
使用JS實現購物車功能01css
具體代碼html
<!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>
效果圖
樣式比較醜,不要介意哈java