<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="fruits" action="" method="get">
您喜欢的水果?<br /><br />
<label><input name="Fruit" type="checkbox" value="" />苹果 10元</label>
<label><input name="Fruit" type="checkbox" value="" />桃子5元 </label>
<label><input name="Fruit" type="checkbox" value="" />香蕉6元 </label>
<label><input name="Fruit" type="checkbox" value="" />梨 3元</label>
<br /><br />
当前价格: <span id="total">0</span>元
</form>
</body>
</html> <script>
var fruits = document.getElementById('fruits')
var labels = fruits.getElementsByTagName('label')
var total = document.getElementById('total')
total.price = 0
// 循环给每个label标签添加price属性存标签内水果的价格
for (var i = 0, len = labels.length i < len i++){
var str = labels[i].innerText
var price = str.replace(/[^0-9]/ig,"")
labels[i].price = Number(price)
}
// 循环给每个label标签注册点击事件
for (var i = 0, len = labels.length i < len i++){
labels[i].onclick = function (e) {
var e = e || window.event
var elm = e.target || e.srcElement
//label点击拦截,只获取input的click
if (elm.tagName !== 'INPUT'){
return
}
var flag = this.firstChild.checked
if (flag){
total.price += this.price
total.innerText = total.price
}
else {
if (total.price){
total.price -= this.price
total.innerText = total.price
}
}
}
}
</script>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)