微信小程序循環動態添加刪除列表


主要實現微信小程序動態添加刪除列表,解決多個相同事件綁定值問題

效果圖如下

.wxml

<block wx:for="{{scoreList}}" wx:key>
  <view class="cu-bar bg-white solid-bottom margin-top">
    <view class="action">
      <text class="cuIcon-title text-brown"></text> 第{{item.num}}節
    </view>
  </view>
  <view class="cu-form-group">
    <view class="title">分數</view>
    <picker bindchange="scoreChange" value="{{item.score}}" data-num="{{item.num}}" range="{{scoreArr}}">
      <view class="picker">
        {{item.score?scoreArr[item.score]:'請選擇'}}
      </view>
    </picker>
  </view>
</block>
<view class="padding flex flex-wrap justify-between align-center">
  <button class="cu-btn bg-gradual-pink cuIcon-add" bindtap="objectAdd">增加</button>
  <button class="cu-btn bg-gradual-pink cuIcon-move" bindtap="objectMove">減少</button>
</view>

 

.js
 Page({
   data: {
     scoreList: [], //分數數組
     scoreArr: ["0分", "1分", "2分", "3分", "4分", "5分"],
     num: 0,
   },
   scoreChange(e) {
     var that = this;
     var tempList = that.data.scoreList;
     for (var i = 0; i < tempList.length; i++) {
       //找到所選的下拉框賦值
       if (tempList[i]["num"] == e.currentTarget.dataset.num) {
         tempList[i]["score"] = e.detail.value;
         break;
       }
     }
     //改變后的值賦值scoreList重新綁定
     that.setData({
       scoreList: tempList
     })
     console.log('scoreList=' + JSON.stringify(that.data.scoreList)) //最終提交到后台得到數據
   },
   //添加一個列表
   objectAdd(e) {
     var that = this
     var addlist = this.data.scoreList;
     var obj = {
       score: null,
       num: this.data.num + 1
     }
     addlist.push(obj)
     this.setData({
       scoreList: addlist,
       num: this.data.num + 1
     })
   },
   //減少一個列表 從最后一個開始減少
   objectMove(e) {
     if (this.data.scoreList.length > 0) {
       this.data.scoreList.splice(this.data.scoreList.length - 1, 1);
       this.setData({
         scoreList: this.data.scoreList,
         num: this.data.num - 1,
       })
     }
   }
 })

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM