微信小程序如何自定义单选和多选

实现单选

实现效果:点击显示单选状态,每次仅能点击一个元素。

实现方式:

wxml: 

{{item}}

 item_list是单选的元素,class定义了选中和未选中的显示形式,changeColor更新点击元素。

 .wxss 

.choose{
  color: red;
  background-color: white;
  font-weight: bold;
}
.no-choose{
  color:black
}

定义选中和未选中的显示样式。

.js 

data:{
    item_list:['牛肉粉','小吃','加料','饮料']
},  
changeColor(e){
    this.setData({
      menu_index: e.currentTarget.dataset.info,
    });
  }

changeColor实时更新点击元素信息。 

实现多选

实现效果:点击多个元素均能显示点击状态。

再次点击可取消选择:

.wxml

{{item}}

 item_list是单选的元素,class定义了选中和未选中的显示形式,changeColor更新点击元素。

.wxss 

.choose{
  color: red;
  background-color: white;
  font-weight: bold;
}
.no-choose{
  color:black
}

定义选中和未选中的显示样式。 

 .js 

data:{
    item_list:['牛肉粉','小吃','加料','饮料']
},  
changeColor(e){
    var m_index = this.data.menu_index
    var index = e.currentTarget.dataset.index
    var m = "menu_index."+ e.currentTarget.dataset.index
    if(m_index[index]==index){
      this.setData({
        [m]: -1
      })
    }else{
      this.setData({
        [m]: e.currentTarget.dataset.index
      })
    }
}

changeColor实时更新点击元素信息,将已点击元素保存包m_index,当元素处于选中状态m_index[index]的值等于传回的index,当元素再次被点击,取消点击状态时, m_index[index]=-1。

更多内容欢迎关注。

有用的话欢迎赞赏。

 

你可能感兴趣的:(微信小程序,微信小程序,小程序)