javascript開發購物車之函數實現加號功能
下面我們就來看html部分的程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> table{width:350px;border:1px solid #eee;text-align:center;} .tr2{height:50px;} input{width:30px;height:20px;text-align: center;} a{text-decoration:none} </style> </head> <body> <table cellspacing="0" cellpadding="0" border="1"> <tr> <th>名称</th> <th>单价</th> <th>数量</th> <th>总价</th> </tr> <tr class="tr2"> <td>手表</td> <td id="price">1999</td> <td> <a href="#" id="a1" class="tp1">-</a> <input type="text" value="1" id="count" > <a href="#" id="a2" class="tp2">+</a> </td> <td id="total">1999</td> </tr> <tr class="tr2"> <td>手机</td> <td id="price_1">2000</td> <td> <a href="#" id="a1" class="tp1">-</a> <input type="text" value="1" id="count_1"> <a href="#" id="a2" class="tp2">+</a> </td> <td id="total_1">2000</td> </tr> </table> </br> </body> </html>
如上程式碼,我們有2個商品,如果我們每次多一個商品,都寫一次加減號的功能,那麼程式碼就太多了,雖然也可以,但是不可取,所以我們下面可以來做一個函數
我們分析下,函數的參數有哪些?
其實做加減功能,然後總價發生變化,我們需要的就是3個參數,單價,總價,數量
大家看上面代碼中的顯示單價的單元格, id 是 price 總價單元格,id 是 total 第一個商品文字方塊的 id 是 count
接下來,我們看儲存格的程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> table{width:350px;border:1px solid #eee;text-align:center;} .tr2{height:50px;} input{width:30px;height:20px;text-align: center;} a{text-decoration:none} </style> </head> <body> <table cellspacing="0" cellpadding="0" border="1"> <tr> <th>名称</th> <th>单价</th> <th>数量</th> <th>总价</th> </tr> <tr class="tr2"> <td>手表</td> <td id="price">1999</td> <td> <a href="#" id="a1" class="tp1" onclick="a2('price','total','count')">-</a> <input type="text" value="1" id="count" onblur="a3('price','total','count')"> <a href="#" id="a2" class="tp2" onclick="a1('price','total','count')">+</a> </td> <td id="total">1999</td> </tr> <tr class="tr2"> <td>手机</td> <td id="price_1">1999</td> <td> <a href="#" id="a1" class="tp1" onclick="a2('price_1','total_1','count_1')">-</a> <input type="text" value="1" id="count_1" onblur="a3('price_1','total_1','count_1')"> <a href="#" id="a2" class="tp2" onclick="a1('price_1','total_1','count_1')">+</a> </td> <td id="total_1">1999</td> </tr> </table> </br> </body> </html>
如上程式碼,我們給加碼減號都綁定了一個點擊事件,裡面有3個參數 商品單價 price 和price_1 總價total 和total_1 數量count 和count_1
下面我們來實現加號功能##下面來看以下完整程式碼:看看實現的效果怎麼樣
<script type="text/javascript"> function a1(td,td2,id){ var price = document.getElementById(td).innerHTML;//获得单价 var total = document.getElementById(td2).innerHTML;//获得总价 var v1 = parseInt(document.getElementById(id).value);//获得数量 document.getElementById(id).value = v1+1; //获取点击后的数量 document.getElementById(td2).innerHTML = parseInt(price) * parseInt(v1+1); //总价格等于单价乘以点击后的数量值 } </script>
看上面的例子,無論我有多少個商品,點擊加號,價格不同,總價也不一樣的,所以使用這樣的方法會方便簡單一點