如何在for循环下创造的多个view中,改变其中一个view的颜色?
发布于 5 年前 作者 xiuying68 10726 次浏览 来自 问答

这是在for循环下出来的多个view,如何单击其中一个,就改变被点击的颜色。

我写出来是单击其中一个,全部都改变,小白求救!!!

5 回复

点击的时候获得clickedIndex

wx:if=’{{index==clickedIndex}}’

class="activeIndex == index ? ‘active’ : ‘normal’ "

统一回复:谢谢各位回复,昨天研究好久,已经实现该功能了。我用来两个视图层,判断status的状态来决定展示哪一个。

//xml  
  <view   wx:for="{{best_contents2}}" wx:key="id"  >

  <view wx:if="{{item.status==0}}" class="item2_content1_datas" id="{{index}}" catchtap="choice_achievement" >
 <view>xxxxx</view>
        </view>

  <view wx:if="{{item.status==1}}" class="item2_content1_datas" id="{{index}}" catchtap="choice_achievement" >
 <view>xxxxx</view>
        </view>
</view>

//js
//best_contents2为循环list
choice_achievement:function(e){    
    var  items_id=e.currentTarget.id
    var Best_content2=this.data.best_contents2
    for (var i in Best_content2){
      if(i==items_id){
        if (Best_content2[i].status == 0) {
          Best_content2[i].status = parseInt(Best_content2[i].status) + 1
        }
      }
    }
    this.setData({
      best_contents2: Best_content2,
    })
  },

加个if判断,对比下点击的key值。

<view wx:for='{{list}}' class="{{activeIndex===index?'active':''}}" bindtap='checkItem' data-index='{{index}}'></view>

Page({
  data:{
    activeIndex:0,//给了个默认值 可以为null
  },
  checkItem(e){
    const {index} = e.currentTarget.dataset;
    const {activeIndex} = this.data;
    if(index==activeIndex){
      return 
    }
    this.setData({
      activeIndex:Number(index)
   })
  }
})
回到顶部