利用localStorage实时显示购物车小计和总价页面显示:
和昨天的原理相同,本地存储同时实时循环计算总价之和,注意循环时候的先清空再计算
Success is getting what you want, happiness is wanting what you get.
成功是得其所想,幸福是想其所得!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
document.addEventListener('DOMContentLoaded',function(){
var aInp=document.querySelectorAll('input');
var oPer=document.getElementsByTagName('em');
var oStotal=document.getElementsByTagName('i');
var oDiv=document.getElementById('div1'); for(var i=0;i<aInp.length;i++){
(function(index){
//当aInp中的数字为0时清除localsotage中的数据
if(aInp[index].value=='0'){
delete localStorage[index];
}
//当aInp中数字发生变化的时候存储localstorage
aInp[index].onchange=function(ev){
localStorage[index]=parseFloat(oPer[index].innerHTML)*aInp[index].value;
oStotal[index].innerHTML='小计'+Number(localStorage[index]);
//获取localStorage并显示在总价中
var sum=0;
for(var name in localStorage){
sum+=Number(localStorage[name]);
oDiv.innerHTML='总价:'+sum;
}
};
})(i);
}
},false);
</script>
</head>
<body>
<div>
<p>商品名称:苹果</p>
<input type="number" min="0" value="0">
<em>3$</em><br><br>
<i></i>
</div>
<div>
<p>商品名称:橘子</p>
<input type="number" min="0" value="0">
<em>6$</em><br><br>
<i></i>
</div>
<div>
<p>商品名称:香蕉</p>
<input type="number" min="0" value="0">
<em>9$</em><br><br>
<i></i>
</div>
<div id="div1">0</div>
</body>
</html>