javascript - 如何计算localStorage中的总量和总计?

标签 javascript jquery

这是我的购物车:

enter image description here

我现在遇到的问题是,总量和总计不是用新值相加而是用新值替换,以便它显示最后一个值。我想增加值(value)。

这是要在底部添加总数量和总小计的脚本:

function calTotal(param)
       {
//this carries the latest value for quantity
           var qty = $('td.qty_'+param+' input[type=text]').val();
//this carries the latest value for subtotal
           var total = $('span.sub_total_'+param+'').text();
//this shows the values respectively in the white row below
           $('span.qty_1').text(qty);
           $('span.total').text(total);
//I'm trying to add the values in localStorage but it shows in string form.
           localStorage.quantity += parseInt(qty);
           alert(localStorage.quantity);


       }


//I'm trying to add the values in localStorage but it shows in string form.For instance when first item's quantity key in '2' it should show 2. WHen next item quantity keyed in '4' it must add prev value and new value. But it shows 24 which is string, no math performed. How to solve this, please?

           localStorage.quantity += parseInt(qty);
           alert(localStorage.quantity);

最佳答案

本地存储存储键和值,其中值也是字符串。如果你想对一个数值进行操作,你需要从本地存储获取它,将其解析为整数,执行操作并再次存储它:

var value = parseInt(localStorage.getItem("value"));
value += 5;
localStorage.setItem("value", value);

关于javascript - 如何计算localStorage中的总量和总计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34512493/

相关文章:

javascript - 检测用户的 Intent 是点击还是在触觉设备上向上/向下滚动页面

javascript - 咕噜连接 : Use file instructions a la Codekit

javascript - 如何使用 Hightchart-ng 制作 Highcharts 半圆 donut chart

javascript - 从内部函数更改 AngularJS 作用域变量

javascript - 动态创建 Bootstrap 元素

javascript - 将对象推送到数组,并使用属性选择器

javascript - 如何使用 leaflet.js 提高将大量特征插入 map 的性能

javascript - 关于克隆/复制TR的一些问题

javascript - 如何从谷歌自定义搜索 API onclick 而不是 onload 加载图像

javascript - 生成图形图表报告