时间:2022-05-27 09:46:08 | 栏目:JavaScript代码 | 点击:次
本文实例为大家分享了js实现购物车加减和价格运算的具体代码,供大家参考,具体内容如下
主要实现功能:购物车的加减,单件商品价格的运算,总价格的运算。价格保留两位小数。
<div class="content"> <div class="logo"> <img src="images/dd_logo.jpg"><span onclick="guan()">关闭</span> </div> <div class="cartList" id="zong"> <ul> <li >¥21.90</li> <li><input type="button" name="minus" value="-" onclick="jian()"><input type="text" name="amount" value="1" id="shang"><input type="button" name="plus" value="+" onclick="jia()"></li> <li>¥<input type="text" name="price" value="21.90" id="yiqian"></li> <li><p onclick="shou()">移入收藏</p><p onclick="shan()">删除</p></li> </ul> <ul> <li >¥24.00</li> <li><input type="button" name="minus" value="-" onclick="jian1()"><input type="text" name="amount" value="1" id="shang1"><input type="button" name="plus" value="+" onclick="jia1()"></li> <li>¥<input type="text" name="price" value="24.00"id="erqian" ></li> <li><p onclick="shan()">移入收藏</p><p onclick="shan()">删除</p></li> </ul> <ol> <li id="totalPrice" > 0.00</li> <li><span onclick="jie()">结 算</span></li> </ol> </div> <h3 id="shijian">现在是:</h3> </div>
上边是html页面
以下是JS脚本
var price = 0.00; var price1 = 0.00; var price2 = 0.00; function jian() { var i = parseInt(document.getElementById("shang").valueOf().value) - 1; if (i <= 0) { i = 0; } document.getElementById("shang").valueOf().value = i; price1 = 21.90 * i; document.getElementById("yiqian").value=suan(price1); zong(); } function jia() { var i = parseInt(document.getElementById("shang").valueOf().value) + 1; document.getElementById("shang").valueOf().value = i; price1 = 21.90 * i; document.getElementById("yiqian").value=suan(price1); zong(); } function jian1() { var i = parseInt(document.getElementById("shang1").valueOf().value) - 1; if (i <= 0) { i = 0; } document.getElementById("shang1").valueOf().value = i; price2 = 24.00 * i; document.getElementById("erqian").value=suan(price2); zong(); } function jia1() { var i = parseInt(document.getElementById("shang1").valueOf().value) + 1; document.getElementById("shang1").valueOf().value = i; price2 = 24.00 * i; document.getElementById("erqian").value=suan(price2); zong(); } function suan(number) { price = price1 + price2; if (isNaN(number)) { return false; } number = Math.round(number * 100) / 100; var s = number.toString(); var rs = s.indexOf("."); if (rs < 0) { rs = s.length; s += "."; } while (s.length <= rs + 2) { s += "0"; } return s; } function zong() { price = price1 + price2; if (isNaN(price)) { return false; } price = Math.round(price * 100) / 100; var s = price.toString(); var rs = s.indexOf("."); if (rs < 0) { rs = s.length; s += "."; } while (s.length <= rs + 2) { s += "0"; } document.getElementById("totalPrice").innerHTML=s; }
用的是最基本的方式,便于初学者看懂,特别是知识点有短板的额,基本上都能看懂。