小程序动态添加input及删除
wxml部分
js部分
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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'
}
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
也可以不用定义两个数组(名字和手机号),把值加入到循环的input的数组中,contacelist:[{name: ‘’,input: ‘’}]
原文链接:https://blog.csdn.net/MAYA_G/article/details/107768127