js商品价格计算

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<ul id="listUl">
			<li>
				<input type="button" value="-"/>
				<strong>0</strong>
				<input type="button" value="+"/>
				单价:<em>12.5元</em>
				小计:<span>0元</span>
			</li>
			<li>
				<input type="button" value="-"/>
				<strong>0</strong>
				<input type="button" value="+"/>
				单价:<em>10.5元</em>
				小计:<span>0元</span>
			</li>
			<li>
				<input type="button" value="-"/>
				<strong>0</strong>
				<input type="button" value="+"/>
				单价:<em>100元</em>
				小计:<span>0元</span>
			</li>
		</ul>
		<p>商品合计:<span id="allNum">0</span>件,共花费了:<span id="allMoney">0</span>元</p>
		<script>
			window.onload=function(){
				var oUl=document.getElementById("listUl");
				var aLi=oUl.getElementsByTagName("li");
				//封装每个li中数量 单价 小计的函数
				function fn1(oLi){
					var aBtn=oLi.getElementsByTagName("input");
					var oStrong=oLi.getElementsByTagName("strong")[0];
					var oEm=oLi.getElementsByTagName("em")[0];
					var oSpan=oLi.getElementsByTagName("span")[0];
					var n1=oStrong.innerText;
					var n2=parseFloat(oEm.innerText);
					
					aBtn[1].onclick=function(){
						n1++;
						oStrong.innerText=n1;
						oSpan.innerText=n1*n2+"元";	
						fn2("strong","allNum");
						fn2("span","allMoney");
					}
					aBtn[0].onclick=function(){
						n1--;
						if(n1<0){
							n1=0;
						}
						oStrong.innerText=n1;
						oSpan.innerText=n1*n2+"元";
						fn2("strong","allNum");
						fn2("span","allMoney");
					}
				}
				for(var i=0;i<aLi.length;i++){
					fn1(aLi[i])
				}
				//封装商品总数,和总费用函数
				function fn2(ht1,id){					
					var arr1=[];
					var allNum=0;
					for(var i=0;i<aLi.length;i++){
						var strong=aLi[i].getElementsByTagName(ht1);
						for(var j=0;j<strong.length;j++){
							arr1.push(strong[j]);
						}
					}
					for(var i=0;i<arr1.length;i++){
						allNum+=parseFloat(arr1[i].innerText);
					}
					document.getElementById(id).innerText=allNum;					
				}
				
			}
		</script>
	</body>
</html>

欢迎分享本文,转载请保留出处:前端ABC » js商品价格计算

赞 (3)
分享到:更多 ()

发表评论 0