微信小程序 循环列表添加点击事件和样式

如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/> 中的输入内容,<switch/> 的选中状态),需要使用 wx:key 来指定列表中项目的唯一的标识符。

wx:key 的值以两种形式提供

  1. 字符串,代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。
  2. 保留关键字 *this 代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字,如:numberArray: [1, 2, 3, 4]

wxml文件:

<view class="userList" wx:for="{{items}}" wx:key="{{item.userId}} wx:for-index="idx"">
        <view class="{{userCellId==idx?'userCellActive':'userCell'}}" data-idx="{{idx}}" bindtap="userListAction">{{item.name}}</view>
</view>

 

1、page.data里设一个变量,比如userCellId(JS文件在下面?)
2、列表项里增加一个属性data-id="{{idx}}" 
3、在列表项的userListAction事件里this.setData({userCellId: e.target.dataset.idx}) 
4、列表项的class里根据userCellId设置不同样式,如class="{{userCellId==idx?'userCellActive':'userCell'}}"
5、wxss里定义.userCellActive和.userCell样式的背景颜色。

 

 

JS文件

 

Page({
  data:{
    items:[
      {
        userId: 1,
        name: "user1", }, { userId: 2, name: "user2", }, { userId: 3, name: "user3", } ], userCellId: 0 }, userListAction:function(e){
   console.log(`点击了${e.target.dataset.idx}`) this.setData({ userCellId: e.target.dataset.idx }) } })

 

 

wxss文件

.userCell{
    background-color: red;
}

.userCellActive{
    background-color: green;
}

 

转载于:https://www.cnblogs.com/shen5214444887/p/6762368.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值