微信小程序之实现循环动态添加和删除输入框

时间:2024-04-06 10:29:56

1.页面代码:

 <block wx:for="{{lists}}" wx:key="{{index}}">
        <van-field class="phone_div" type="number" value="" name="phone" label="电话" placeholder="请输入你的电话" bindchange="bindPhoneDataChang{{index}}" />
      </block>
      <van-button class='="send_code_div"' type="info" disabled="{{disabled}}" bind:click="onAddPhone">
        <text class='code_text'>+</text>
      </van-button>
      <van-button class='="send_code_div"' type="info" disabled="{{disabled}}" bind:click="delList">
        <text class='code_text'>-</text>
      </van-button>

2.js代码:

 data: {
    lists: [{
      value:''
    }]
  },
  onAddPhone: function () {
    var lists = this.data.lists;
    var newData = { value: ''};
    if (lists.length >= 3) {
      Dialog.alert({
        message: '最多再增加2个输入框'
      });
      return;
    }
    lists.push(newData);
    this.setData({
      lists: lists,
    })
  },
  delList: function () {
    var lists = this.data.lists;
    if (lists.length<=1){
      Dialog.alert({
        message: '不能删除默认输入框'
      });
      return;
    }
    lists.pop();  
    this.setData({
      lists: lists,
    })
  }, 
  bindPhoneDataChang0: function (e){
    var up = "lists[" + 0 + "].value";
    this.setData({
      [up]: e.detail
    })
  } , 
  bindPhoneDataChang1: function (e) {
    var up = "lists[" + 1 + "].value";
    this.setData({
      [up]: e.detail
    })
  } ,
  bindPhoneDataChang2: function (e) {
    var up = "lists[" + 2 + "].value";
    this.setData({
      [up]: e.detail
    })
  } ,

css代码:

.phone_div{
 float: left;
 width: 65%;
}

.send_code_div{
  float: left;
  width: 15%;
  }
  .code_text{
    font-size: 11px;
  }

 

 

 

效果展示:

微信小程序之实现循环动态添加和删除输入框

微信小程序之实现循环动态添加和删除输入框