微信小程序判断某个checkbox是否选中(在非checkboxchange事件中)

做购物车的小程序时,点击已被选中的某个商品的加号时


image.png

总计的价格也要跟随商品数量的增加而累加,也就是这个加号的点击事件里,我们要判断当前商品是否是选中状态:我的方法是在checkbox发生改变时,在data中设置一个对应的变量存储当前checkbox的选中状态,可是商品那么多,一个变量肯定是不行的,所以要用数组来存:(数组的索引对应checkbox的索引)
代码已经尽量给全了,其实这里最重要的是

this.setData({
       ['checkstatus['+checkid+']']: true,
     });

用中括号括起来,小程序的变量名就可以用变量来表示了


下面是我的代码,觉得这篇文章对你有帮助的话,给我点个赞吧
模拟数据:

// 模拟数据
var posts_goodsinfo = [{
  pic: 'http://img.hb.aicdn.com/c1fc35df63be17c0b0a23d13a12dbf5697fa5c3227b6c-QBcOiv_fw658', title: '吐鲁番番茄', detail: '秘鲁蓝莓2盒(约125g/盒) 新鲜水果 蓝莓鲜果', weight: '500g', price: 400.00, postid: 1, status: '缺货', count: 4, checked: false, 
  goodsimg:'http://img.hb.aicdn.com/ce1d3867242705f49d216d7fe2429fdde08920ce7e7fa-qsobM7_fw658'},
  {
    pic: 'http://img.hb.aicdn.com/9175fa3d1f28872eb676352f5c175d00089987cc3d06e-GQfBhL_fw658', detail: '四川汉源花椒麻椒大红袍干红花椒卤料调料配料【250克】特产包邮', weight: '500g', price: 400.00, postid: 2, status: '有货', count: 1, checked: true, goodsimg: 'http://img.hb.aicdn.com/136072271f766f9f95c8e82294fc611f03f95db631b31b-rwJLCJ_fw658'
  }, {
    pic: 'http://img.hb.aicdn.com/ac28f1d1e4d092d87a9d2b1844082edffc75c63f3b9e4-5fRQAr_fw658', detail: '2斤装8-12个进口普吉岛去皮小菠萝泰国削皮迷你新鲜菠萝顺丰包邮 ', weight: '500g', price: 400.00, postid: 3, status: '有货', count: 6, checked: false, goodsimg:'http://img.hb.aicdn.com/04cfc246a2ec0b01291ac5e41be3d36335764a0321fec1-db27zg_fw658'
  },
  {
    pic: 'http://img.hb.aicdn.com/9fa49fb48f3002fcc27f35c4daacece2a4457889278bc-TKg5lE_fw658', detail: '天勤新鲜有机甜糯玉米棒粘黏糯米小真空速食营养早餐粗粮10支', weight: '500g', price: 400.00, postid: 4, status: '有货', count: 1, checked: false, goodsimg:'http://img.hb.aicdn.com/8e6576a1b1868d1bafd6be258c9a2621d33f224b140ca6-eBqDf2_fw658'
  }, {
    pic: 'http://img.hb.aicdn.com/287e45caaf9771aa2e8e38f0da754b7c3b99de29b829a-fkEg4U_fw658', detail: '甘福园 四川攀枝花凯特芒果 新鲜当季水果大青芒整箱10斤批发包邮', weight: '500g', price: 400.00, postid: 5, status: '有货', count: 2, checked: false, goodsimg:'http://img.hb.aicdn.com/88b23842ad04f696500073b0e50809091efd283e8a979f-gT7pdE_fw658'
  },
  {
    pic: 'http://img.hb.aicdn.com/7c9d40ee7d3b76d90bd45ed145bbfe110e76056d17ca1-hzSmev_fw658', detail: '现货南非西柚8个大果葡萄柚红心柚子新鲜水果孕妇进口当季时令干', weight: '500g', price: 400.00, postid: 6, status: '有货', count: 1, checked: false, goodsimg:'http://img.hb.aicdn.com/b1f11c8c396bd2303cf8d99e27bf57cd5b274711292431-USFfSJ_fw658'
  }
];
var posts_favourable = [{favid: 1, name: "未使用", value: 0 }, { favid: 2, name:'20元店铺优惠券',value:20}];
var posts_address = [{addressid: 1, name: "陈雅婷", tel: "17756446937", province: "安徽省", city: "六安市", county:"金安区",detail:"开发区大学科技园"},
  { addressid: 2,name: "何远浩", tel: "12345678901", province: "安徽省", city: "六安市", county: "金安区", detail: "开发区大学科技园" }
]
var posts_cart = [{
  pic: 'http://img.hb.aicdn.com/7c9d40ee7d3b76d90bd45ed145bbfe110e76056d17ca1-hzSmev_fw658', detail: '现货南非西柚8个大果葡萄柚红心柚子新鲜水果孕妇进口当季时令干', weight: '500g', price: 400.00, postid: 6, status: '有货', count: '1', checked: false, goodsimg: 'http://img.hb.aicdn.com/b1f11c8c396bd2303cf8d99e27bf57cd5b274711292431-USFfSJ_fw658'
}, {
    pic: 'http://img.hb.aicdn.com/9fa49fb48f3002fcc27f35c4daacece2a4457889278bc-TKg5lE_fw658', detail: '天勤新鲜有机甜糯玉米棒粘黏糯米小真空速食营养早餐粗粮10支', weight: '500g', price: 400.00, postid: 4, status: '有货', count: '1', checked: false, goodsimg: 'http://img.hb.aicdn.com/8e6576a1b1868d1bafd6be258c9a2621d33f224b140ca6-eBqDf2_fw658'
  }, {
    pic: 'http://img.hb.aicdn.com/287e45caaf9771aa2e8e38f0da754b7c3b99de29b829a-fkEg4U_fw658', detail: '甘福园 四川攀枝花凯特芒果 新鲜当季水果大青芒整箱10斤批发包邮', weight: '500g', price: 400.00, postid: 5, status: '有货', count: '2', checked: false, goodsimg: 'http://img.hb.aicdn.com/88b23842ad04f696500073b0e50809091efd283e8a979f-gT7pdE_fw658'
  }]
module.exports = { 
  postlist: posts_goodsinfo,
  postfav: posts_favourable,
  postaddress: posts_address ,
  postcart: posts_cart
  //给这个数组变量赋值,让这个数组可以通过这个exports出去
}

wxml:

<!--pages/cart/cart.wxml-->
<view class='cart_bg'>
  <text class='cart_name'>购物车</text>
</view>
<scroll-view class="Wrapscroll-view" data-c_e_id="wx_scroll_view_18790ec8" lower-threshold="50" scroll-y="True"  style="overflow-x: hidden; overflow-y: auto; " upper-threshold="50">
<view class='cart_card_box'>
<block wx:for="{{postsList}}">
  <view class='cart_card' catchtap='onLinkDetail' data-post="{{item.postid}}" >
    <checkbox-group bindchange="checkboxChange" catchtap='onStopEvent' data-checkid='{{index}}'>
      <checkbox class='cart_checkbox' bindtap='onCalcSelect' catchtap='onStopEvent'  checked="{{selectedAllStatus}}" ></checkbox>
    </checkbox-group>
    <image src='{{item.pic}}' class='cart_card_img' model="aspectFit"></image>
    <view class='cart_card_detail'>
      <image src='/images/can.png' class='delate' catchtap='bindDelateGoods' data-delate='{{index}}'></image>
      <text class='detail_text'>{{item.detail}}</text>
      <text class='detail_price'>¥{{item.price}}</text>
      <view class='stepper'>
        <text type='number'  catchtap='bindMinus' data-index='{{index}}'>-</text>
        <input bindinput='bindManual' value='{{item.count}}' disabled></input>
        <text catchtap='bindPlus' data-index='{{index}}' data-checked='{{status}}'>+</text>
      </view>
    </view>
  </view>  
</block>
</view> 
</scroll-view>
<view class='bottom_bar'>
<checkbox-group bindchange="bindCalcAll">
 <checkbox class='all_checkbox' catchtap='bindSelectAll' checked='{{tag}}'></checkbox>  
</checkbox-group>
 <view class='rightall'>
   <text>总计:</text><text class='red'>¥{{sum}}</text>
   <button catchtap='onCalcSelect'>结算</button>
 </view>
</view>

js:

var postData = require('../../common.js');
var flag = 0;
// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectedAllStatus:false,
    sum: 0,
    checkstatus:[],
    buylist:[0,1]
  },
  //事件处理函数
  /*点击减号*/
  bindMinus: function (event) {
    var index = event.currentTarget.dataset.index;
    var postList = this.data.postsList;
    var num = postList[index].count;
    var that = num;
    if (num > 1) {
      num--;
    }
    postList[index].count=num;
    this.setData({
      postsList:postList
    }); 
    //判断当前商品是否被选中
    // console.log(event)
    if (this.data.checkstatus[index] == true) {
      var sum = this.data.sum;
      sum = sum - (that - num) * postList[index].price;
      this.setData({
        sum: sum,
      });
    } 
  },
  /*点击加号*/
  bindPlus: function (event) {
    var index = event.currentTarget.dataset.index;
    var postList = this.data.postsList;
    var num = postList[index].count;
    var that=num;
    num++;
    postList[index].count = num;
    this.setData({
      postsList: postList
    });
    var checkid='checkid'+index
    //判断当前商品是否被选中
    if (this.data.checkstatus[index] == true){
      var sum = this.data.sum;
      sum = sum + (num - that) * postList[index].price;
      this.setData({
        sum: sum,
      });
    };
    console.log(this.data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      postsList: postData.postcart
    });
  },
  /**
   * 单个复选框的选中、取消事件
   */
  checkboxChange: function(e) {
   if(e.detail.value.length==1) {
     var checkid=e.target.dataset.checkid;
     var sum = this.data.sum;
     var postsList = this.data.postsList;
     sum=sum+postsList[checkid].price*postsList[checkid].count;
     this.setData({
       sum:sum,
       ['checkstatus['+checkid+']']: true,
     });
     //判断是否所有商品都被选中
     var checkstatus = this.data.checkstatus;
     var p=true
     for (var i = 0;i<postsList.length;i++) {
       if (checkstatus[i] == false || checkstatus[i] ==undefined){
         p=false;
       };
     };
     if(p) {
       this.setData({
         tag: true
       });
     }else {
       this.setData({
         tag: false
       });
     };
   }else{
     var checkid = e.target.dataset.checkid;
     var sum = this.data.sum;
     var postsList = this.data.postsList;
     sum = sum - postsList[checkid].price * postsList[checkid].count;
     this.setData({
       sum: sum,
       ['checkstatus[' + checkid + ']']: false,
     //取消勾选后将全选置false
       tag: false
     });
   };
    console.log(this.data.checkstatus);
  },
  /**
   * 全选事件(全选按钮和计算总价)
   */
  bindCalcAll: function (e) {
    var postsList = this.data.postsList;
    var checkstatus=[];
    var sum = 0;
    if (e.detail.value.length == 1) {
      for (var i = 0; i < postsList.length; i++) {
        sum=sum+postsList[i].price*postsList[i].count;
        checkstatus[i]=true;
      };
      this.setData({
        sum:sum,
        selectedAllStatus: true,
        checkstatus:checkstatus
      })
    }else{
      for (var i = 0; i < postsList.length; i++) {
        checkstatus[i] = false;
      };
      this.setData({
        sum: sum,
        selectedAllStatus: false,
        checkstatus: checkstatus
      })
    }
  },
  //删除事件
  bindDelateGoods: function(e) {
    var that=this;
    wx.showModal({
      title: '提示',
      content: '确认删除这件商品吗',
      success: function (res) {
        if (res.confirm) {
          var delateid = e.target.dataset.delateid;
          var postsList = that.data.postsList;
          postsList.splice(delateid, 1);
          that.setData({
            postsList: postsList
          })
        } else {
          console.log('用户点击取消')
        }
      }
    })
  },
  //跳转事件
  onLinkDetail: function(e) {
    var postid = e.currentTarget.dataset.post;
    console.log(postid)
    wx.navigateTo({
      url: '../detail/detail?id=' + postid,
    })
  },
    //结算
  onCalcSelect: function(e) {
    var checkstatus = this.data.checkstatus;
    var cartlist = this.data.postsList;
    var cartarray=[]
    for (var i = 0; i < checkstatus.length;i++) {
      if (checkstatus[i]===true) {
        cartarray.push(cartlist[i].postid);
      } 
    };
    if (cartarray.length!=0){
      var model = JSON.stringify(cartarray);
      console.log(model)
      wx.navigateTo({
        url: '../buyit/buyit?cartlist=' + model,
      });
    }; 
  },
  //阻止事件冒泡
  onStopEvent:function(){},
})

wxss:

/* pages/cart/cart.wxss */
.Wrapscroll-view {
  padding:0;
position:fixed;
background:#ebebeb;
top:100rpx;
padding-bottom:200rpx;
}
.cart_bg {
background:#ecc30d;
width:750rpx;
height:100rpx;
position:fixed;
top:0;
font-size: 16px;
}
.cart_bg .cart_name {
  color:#464544;
  text-align: center;
  display:block;
  font-size: 18px;
  line-height: 100rpx;
}
.cart_bg .cart_quantity {
  font-size:14px;
  padding-left:20rpx;
  color:#464544;
  margin-top:17rpx;
  display:block;
}
.cart_bg .cart_edit {
  position: absolute;
  top: 25rpx;
  display: inline-block;
  font-size: 16px;
  color: #464544;
  right: 20rpx;
}
.cart_card_box {
  position:absolute;
  width:750rpx;
}
.cart_card {
width:700rpx;
margin:30rpx auto;
background:#fff;
border-radius:15px;
display:block;
height:232rpx;
position:relative;
}
.cart_card_img {
width:180rpx;
height:180rpx;
margin:26rpx 20rpx;
margin-left:66rpx;
}
/*主容器*/
.stepper {
width:180rpx;
height:54rpx;
border:1px solid #ccc;
border-radius:3px;
position:absolute;
right:10rpx;
bottom: 0;
}
/*加号和减号*/
.stepper text {
float:left;
width:50rpx;
line-height:50rpx;
text-align:center;
color: #ccc;
}
/*数值*/
.stepper input {
  display: inline-block;
  width:38px;
height:50rpx;
float:left;
margin:0 auto;
text-align:center;
font-size:12px;
border-left:1px solid #ccc;
border-right:1px solid #ccc;
color:#333;
}
.cart_card_detail {
float:right;
width:406rpx;
display:flex;
flex-direction:column;
align-items:;
margin:26rpx 0;
height:180rpx;
margin-top:26rpx;
margin-right:20rpx;
position: relative;
}
.cart_card_detail .delate {
position:absolute;
width:60rpx;
height:60rpx;
right:10rpx;
top:34rpx;
}
.cart_card_detail .detail_text {
font-size:13px;
overflow:hidden;
text-overflow:ellipsis;
display:-webkit-box;
-webkit-box-orient:vertical;
-webkit-line-clamp:2;
margin:8px 0;
min-height:35px;
text-align:left;
width:277rpx;
}
.cart_card_detail .detail_price {
  font-size:16px;
  color:red;
  position:absolute;
  bottom:10rpx;
  left:0;
}
/*  重写 checkbox 样式  */
/* 未选中的 背景样式 */
checkbox .wx-checkbox-input{
   border-radius: 50%;/* 圆角 */
   width: 40rpx; /* 背景的宽 */
   height: 40rpx; /* 背景的高 */
}
/* 选中后的 背景样式 (红色背景 无边框 可根据UI需求自己修改) */
checkbox .wx-checkbox-input.wx-checkbox-input-checked{
   border: none;
   background: red;
}
/* 选中后的 对勾样式 (白色对勾 可根据UI需求自己修改) */
checkbox .wx-checkbox-input.wx-checkbox-input-checked::before{
   border-radius: 50%;/* 圆角 */
   width: 40rpx;/* 选中后对勾大小,不要超过背景的尺寸 */
   height: 40rpx;/* 选中后对勾大小,不要超过背景的尺寸 */
   line-height: 40rpx;
   text-align: center;
   font-size:30rpx; /* 对勾大小 30rpx */
   color:#fff; /* 对勾颜色 白色 */
   background: transparent;
   transform:translate(-50%, -50%) scale(1);
   -webkit-transform:translate(-50%, -50%) scale(1);
}
.cart_checkbox {
position:absolute;
left:10rpx;
height:232rpx;
line-height:232rpx;
}
.bottom_bar {
width:750rpx;
height:100rpx;
background:#fff;
position:fixed;
bottom:0;
border-top:1px solid #eee;
}
.bottom_bar .all_checkbox {
  position:absolute;
top:30rpx;
left:35rpx;
}
.bottom_bar .rightall {
  float: right;
}
.bottom_bar .rightall text {
height:100rpx;
display:inline-block;
line-height:100rpx;
vertical-align:bottom;
font-size:14px;
}
.bottom_bar .rightall .red {
  color: red;
  margin-right:15rpx;
}
.bottom_bar .rightall button {
display:inline-block;
height:100rpx;
vertical-align:bottom;
width:135rpx;
background:#ECC30D;
border-radius:0;
font-size:16px;
line-height: 100rpx;
color: #333;
}
button::after {
  border: none;
}

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):