wxml部分
原理: 定义一个空数组,通过点击添加按钮向空数组中添加空值占位,通过在wxml中循环这个数组,来实现input 的添加和删除
<block wx:for="{{contacelist}}">
<view class="contact-person" >
<view class="page-section">
<view class="weui-cells__title">姓名</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<input class="weui-input" data-index="{{index}}" name="{{'contentName' + index}}" value='{{nameVal[index]}}' bindinput='getNameVal' placeholder="请输入" />
</view>
</view>
</view>
<view class="page-section">
<view class="weui-cells__title">手机号</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<input class="weui-input" data-index="{{index}}" name="{{'contentPhone' + index}}" type="number" value='{{phoneVal[index]}}' bindinput='getPhoneVal' maxlength="11" placeholder="请输入" placeholder-style="color:#acacac" />
</view>
</view>
</view>
<view class="delete-btn" data-id="{{index}}" bindtap="handleDeleteProduct">删除</view>
</view>
</block>
<button class="sub-btn add-btn" style="background-color: #ff9600" type="primary" bindtap='add'>+ 添加职工代表</button>
</block>
js部分
原理: 分别定义两个记录手机号和姓名的数组,实现删除添加时保留输入记录
data: {
// 联系人列表(添加input用,无实际作用)
contacelist: [{}],
// 联系人名称
nameVal: [],
// 联系人手机号
phoneVal: []
},
/**
* 添加联系人
*/
add(e) {
// 点击添加按钮,就往数组里添加一条空数据
var _list = this.data.contacelist;
_list.push({})
this.setData({
contacelist: _list
})
},
//获取姓名input的值
getNameVal:function(e){
var nowIdx=e.currentTarget.dataset.index;//获取当前索引
var val=e.detail.value;//获取输入的值
var oldVal=this.data.nameVal;
oldVal[nowIdx]=val;//修改对应索引值的内容
this.setData({
nameVal:oldVal
})
},
//获取手机号input的值
getPhoneVal:function(e){
var nowIdx=e.currentTarget.dataset.index;//获取当前索引
var val=e.detail.value;//获取输入的值
var oldVal=this.data.phoneVal;
oldVal[nowIdx]=val;//修改对应索引值的内容
this.setData({
phoneVal:oldVal
})
},
// 删除input
handleDeleteProduct: function (e) {
let contacelist = this.data.contacelist
let nameVal = this.data.nameVal
let phoneVal = this.data.phoneVal
let productIndex = e.currentTarget.dataset.id
if (this.data.contacelist.length>1) {
contacelist.splice(productIndex, 1)
nameVal.splice(productIndex, 1)
phoneVal.splice(productIndex, 1)
this.setData({
contacelist,
nameVal,
phoneVal
})
if (contacelist[productIndex]) {
this.setXmove(productIndex, 0)
}
} else {
this.setXmove(productIndex, 0)
wx.showToast({
title: '至少保留一个职工代表',
icon: 'none'
})
}
},
也可以不用定义两个数组(名字和手机号),把值加入到循环的input的数组中,contacelist:[{name: ‘’,input: ‘’}]