JavaScript.购物车

今天小阿飞来给大家分享一个简单的购物车案例

直接上代码叭:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>计算每一行总价的功能</title>
	</head>
	<body>
		<table border>
			<tr>
				<td>全选<input type="checkbox"/></td>
				<td>名称</td>
				<td>单价</td>
				<td>个数</td>
				<td>总价</td>
				<td>操作</td>
			</tr>
			<tr>
				<td><input type="checkbox"/></td>
				<td>🍍🍍🍍</td>
				<!--可以通过class类名拿元素-->
				<td class="price">9.9</td>
				<!-- contenteditable是否能修改表格内容 -->
				<td contenteditable="true" class="count">2</td>
				<td class="sum">9.9</td>
				<td>
					<button type="button">+</button>
					<button type="button">-</button>
					<button type="button">删除</button>
					</td>
			</tr>
			<tr>
				<td><input type="checkbox"/></td>
				<td>🍈🍈🍈</td>
				<!--可以通过class类名拿元素-->
				<td class="price">10.99</td>
				<!-- contenteditable是否能修改表格内容 -->
				<td contenteditable="true" class="count">1</td>
				<td class="sum">9.9</td>
				<td>
					<button type="button">+</button>
					<button type="button">-</button>
					<button type="button">删除</button>
					</td>
			</tr>
			<tr>
				<td><input type="checkbox"/></td>
				<td>🍓🍓🍓</td>
				<!--可以通过class类名拿元素-->
				<td class="price">19.9</td>
				<!-- contenteditable是否能修改表格内容 -->
				<td contenteditable="true" class="count">2</td>
				<td class="sum">9.9</td>
				<td>
					<button type="button">+</button>
					<button type="button">-</button>
					<button type="button">删除</button>
					</td>
			</tr>
		</table>
		<script type="text/javascript">
		  // 计算表格每一行中的总价并赋值给这一行的总价列的函数
		  function calc(tr){//调用时要传入tr
			  // 通过tr拿到price,count
			  // Elements带s的方法都是返回一个集合,尽管只有一列叫price
			  //取这个集合的第一个的值(但是只有input和下拉框select才可以用.value来获取值)
			  // 其他的标签可以用.textContent来得到值或者修改值
			  var price=tr.getElementsByClassName('price')[0].textContent
			  var count=tr.getElementsByClassName('count')[0].textContent
			  //算出总价并赋值给sum
			  tr.getElementsByClassName('sum')[0].textContent=(price*count).toFixed(2)
		  }
		 //窗口(window)的加载事件  会在整个页面加载完成(打开)之后执行
			window.onload=()=>{
				// 窗口加载完成后要做的:
				// 1.计算每一行的总价
				// 获得页面中所有的行
				var trs=document.getElementsByTagName('tr')
				//a.使用foreach
				// for(let tr in trs){//用in遍历下标
				// 	// 下标并不一定是数字类型所以最好不要用(!tr)来判断
				// 	if(tr==0)continue//下标0代表第一行
				// 	// 将除了第一行外的都传入
				// 	calc(trs[tr])
				// }
				// b.使用for循环
				for(let i=1;i<trs.length;i++){
					calc(trs[i])//让有商品的行的价格都计算显示
				}
			}
		</script>
	</body>
</html>

 简单的展示一下运行效果叭:

 

就写到这叭^_^ 

  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值