最好能给出代码,谢谢!
商品计算器,购物车模块一
商品 | 单价(元/件) | 数量(件) | 小计(元) |
---|---|---|---|
iPad | 0 | ||
iPhone | 0 | ||
iMac | 0 | ||
总计: |
每次价格改动的时候,你都要调用一个计算总价的 方法,来遍历所有的商品和数量 计算价格。
每项小计都算出来了,把它们加起来不就行了吗。for循环里直接做就可以了。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="description" content=""> <meta name="keywords" content=""> <title>商品计算器,购物车模块一</title> <!-- <script type="text/javascript" src="jquery-1.10.1.min.js?1.2.1"></script> --> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js?1.2.1"></script> <style type="text/css"> * { /*line-height: 30px;*/ padding: 0px; margin: 0px; } table { text-align: center; margin: 30px; } td, th { padding: 8px; } input { width: 120px; } </style> </head> <script type="text/javascript"> $(document).ready(function() { //乘法函数,用来得到精确的乘法结果 //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 //调用:accMul(arg1,arg2) //返回值:arg1乘以arg2的精确结果 function accMul(arg1, arg2) { var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length } catch (e) {} try { m += s2.split(".")[1].length } catch (e) {} return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m) } //加法函数,用来得到精确的加法结果 //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 //调用:accAdd(arg1,arg2) //返回值:arg1加上arg2的精确结果 function accAdd(arg1, arg2) { var r1, r2, m; try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 } m = Math.pow(10, Math.max(r1, r2)) return (parseInt(arg1 * m, 10) + parseInt(arg2 * m, 10)) / m } function aa() { var price; var total_price = 0; for (i = 0; i < $('tr').size() - 2; i++) { // 小计函数 var price = accMul($('.price').eq(i).val(), $('.num').eq(i).val()); total_price = accAdd(total_price, price); $('.subtotal').eq(i).text(price); $('.total_price').text(total_price) } } $('input').change(function() { aa(); }) }); </script> <body> <table border="1" width="600" cellspacing="0" cellpadding="0" bordercolor="#b2b2b2" style="border-collapse:collapse"> <tr> <th>商品</th> <th>单价(元/件)</th> <th>数量(件)</th> <th>小计(元)</th> </tr> <tr> <td>iPad</td> <td> <input type="text" class="price" value="0"> </td> <td> <input type="text" class="num" value="0"> </td> <td class="subtotal">0</td> </tr> <tr> <td>iPhone</td> <td> <input type="text" class="price" value="0"> </td> <td> <input type="text" class="num" value="0"> </td> <td class="subtotal">0</td> </tr> <tr> <td>iMac</td> <td> <input type="text" class="price" value="0"> </td> <td> <input type="text" class="num" value="0"> </td> <td class="subtotal">0</td> </tr> <tr> <td colspan="3">总计:</td> <td class="total_price"></td> </tr> </table> </body> </html>