使用Selector API实现购物车客户端计算

html:

<span style="font-size:18px;"><!DOCTYPE HTML>
<html>
<head>
<title>使用Selector API实现购物车客户端计算</title>
<meta charset="utf-8" />
<style>
	table{width:600px; text-align:center;
		border-collapse:collapse;
	}
	td,th{border:1px solid black}
	td[colspan="3"]{text-align:right;}
	/*tbody>tr>td:last-child{background-color:red}*/
	/*tfoot>tr>td:last-child{background-color:red}*/
</style>
<script src="js/6_2.js"></script>
</head>
<body>
	<table id="data">
		<thead>
			<tr>
				<th>商品名称</th>
				<th>单价</th>
				<th>数量</th>
				<th>小计</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>iPhone6</td>
				<td>¥4488</td>
<td>
	<button οnclick="calc(this)">-</button>
	<!--this指当前事件所在的元素对象
		  何时使用: 如果事件处理中需要使用当前元素对象-->
	<span>1</span>
	<button οnclick="calc(this)">+</button>
</td>
				<td>¥4488</td>
			</tr>
			<tr>
				<td>iPhone6 plus</td>
				<td>¥5288</td>
				<td>
				<button οnclick="calc(this)">-</button>
				<span>1</span>
				<button οnclick="calc(this)">+</button>
				</td>
				<td>¥5288</td>
			</tr>
			<tr>
				<td>iPad Air 2</td>
				<td>¥4288</td>
				<td>
					<button οnclick="calc(this)">-</button>
					<span>1</span>
					<button οnclick="calc(this)">+</button>
				</td>
				<td>¥4288</td>
			</tr>
		</tbody>
		<tfoot>
			<tr>
				<td colspan="3">Total: </td>
				<td>¥14064</td>
			</tr>
		</tfoot>
	</table>
</body>
</html>
</span>


js:

<span style="font-size:18px;">function calc(btn){
  //数量加减
  //查找span
  var span=btn.innerHTML=="+"?
            btn.<span style="color:#cc0000;">previousElementSibling</span>:
            btn.<span style="color:#cc0000;">nextElementSibling</span>;
  //取出span的内容,转为整数,保存在变量n中
  var n=parseInt(span.innerHTML);
  //如果btn是+,就n+1,否则如果n等于1,就继续=1,否则,就n-1。
  n=btn.innerHTML=="+"?n+1:
                  n==1?1:
                       n-1;
  //将n保存回span中
  span.innerHTML=n;

  //计算小计:
  //找到btn的父元素的前一个元素节点,从1位置截取内容,获得单价,转为浮点数,保存在变量price中
  var price=parseFloat(
        btn.parentNode.previousElementSibling
                      .innerHTML.slice(1)
  );
  //计算小计subTotal:price*n
  var subTotal=price*n;
  //找到btn的父元素的下一个元素节点,将其内容直接设置为¥+subTotal.toFixed(2)
  btn.parentNode.nextElementSibling.innerHTML=
                        "¥"+subTotal.toFixed(2);
  
  //计算总价
  //获取tbody中每一行最后一个td
  var subTotals=document.querySelectorAll(
    "#data>tbody>tr>td:last-child"
  );
  //遍历每个td,将内容累加到变量total中
  for(var i=0,total=0;i<subTotals.length;i++){
    total+=parseFloat(subTotals[i].innerHTML.slice(1));
  }
  //将total放入tfoot中最后一个td
document.querySelector("#data>tfoot>tr>td:last-child")
        .innerHTML="¥"+total.toFixed(2);
}</span>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值