//计算数量 countNum: function () { var that = this //遍历数组,把既选中的num加起来 var newList = that.data.buy var allNum = 0 for (var i = 0; i if (newList[i].select == “success”) { allNum += parseInt(newList[i].num) } } parseInt console.log(allNum) that.setData({ num: allNum }) },
4.计算商品金额,代码如下:
//计算金额方法 count: function () { var that = this //选中的订单,数量*价格加起来 var newList = that.data.buy var newCount = 0 for (var i = 0; i if (newList[i].select == “success”) { newCount += newList[i].num * newList[i].price } } that.setData({ count: newCount }) }
5.将购物车中的商品数量添加,代码如下:
//商品数量增加函数 addtion: function (e) { var that = this //得到下标 var index = e.currentTarget.dataset.index // 得到点击的值 var num = e.currentTarget.dataset.num num++ // 把新的值给新的数组 var newList = that.data.buy newList[index].num = num //把新的数组传给前台 that.setData({ buy: newList }) //调用计算数目方法 that.countNum() //计算金额 that.count() },
6.将购物车中的商品数量减少,但数量减少到小于1时,该商品就会消失,代码如下:
//商品数量减少 subtraction: function (e) { var that = this // 得到下标 var index = e.currentTarget.dataset.index //得到点击的值 var num = e.currentTarget.dataset.num //把新的值给新的数组 var newList = that.data.buy //当1件时,点击移除 if (num == 1) { newList.splice(index, 1) } else { num– newList[index].num = num } // 把新的数组传给前台 that.setData({ buy: newList }) //调用计算数目方法 that.countNum() // 计算金额 that.count() },
7.单选商品,结算金额
change: function (e) { var that = this //得到下标 var index = e.currentTarget.dataset.index //得到选中状态 var select = e.currentTarget.dataset.select console.log(e.currentTarget.dataset.select); if (select == “circle”) { var stype = “success” } else { var stype = “circle” } //把新的值给新的数组 var newList = that.data.buy newList[index].select = stype //把新的数组传给前台 that.setData({ buy: newList }) //调用计算数目方法 that.countNum() //计算金额 that.count() },
8.全选商品,并结算金额
全选
//全选 allSelect: function (e) { var that = this //先判断现在选中没 var allSelect = e.currentTarget.dataset.select var newList = that.data.buy if (allSelect == “circle”) { //先把数组遍历一遍,然后改掉select值 for (var i = 0; i newList[i].select = “success” } var select = “success” } else { for (var i = 0; i newList[i].select = “circle” } var select = “circle” } that.setData({ buy: newList, allSelect: select }) //调用计算数目方法 that.countNum() //计算金额 that.count() },