小程序数组添加元素,,微信小程序 数组追加元素
思路:
1.先写好需要展示的样式,和需要添加电话的样式,通过wx:if="{{!item.updateSgin}}"条件语句进行判断 是否是后台数据传过来的(false),还是新添加的(ture);
2.加载数据时,已经定义好数组及把数据放入数组中了;
3.点击添加电话,给一个空的内容,及标志添加样式,追加进数组里,用setData重新赋值;
success: function (res) { wx.hideLoading(); var cust = res.data.dataJson.customerProduct.customer; var custPhones = cust.custPhone.split(',');
//将显示电话,通过,分割字符串,设置一个数组; var custPhoneArr = _this.data.custPhoneArr for (var i = 0; i custPhones.length; i++) { var obj = { custPhone: custPhones[i], updateSgin: false
//标志显示电话 custPhoneArr.push(obj);
//将电话号码放入custPhoneArr数组中;
}
_this.setData({
custPhoneArr: custPhoneArr,
//赋值
})
}
//添加电话
addPhoneShow:function(){ var _this=this; var custPhones = _this.data.custPhoneArr;
//定义一个要使用的变量名 if (custPhones.length = 5) { wx.showToast({ title: '最多添加5个', } else { var obj = { custPhone: "", updateSgin: true
//标志添加电话样式 custPhones.push(obj)
//追加一个内容为空的,(先占个地~) this.setData({ custPhoneArr: custPhones
//重新给custPhoneArr赋值
})
}
},
//添加电话,进行删除功能
delAddShow: function(e) { var _this = this; console.log(e); wx.showModal({ title: '', content: '是否真的要删除', confirmColor:'#3491f0', success: function (res) { if (res.confirm) { var custPhones = _this.data.custPhoneArr var index = e.currentTarget.dataset.index
//点击获取,想要操作元素的下标 custPhones.splice(index, 1);
//使用splice,进行删除元素 console.log(custPhones); _this.setData({ custPhoneArr: custPhones
//重新赋值
li block wx:for="{{custPhoneArr}}" wx:key="item" wx:for-index='i' li wx:if="{{!item.updateSgin}}" view span * /span span 手机 /span span view span id="custPhone{{i}}" {{item.custPhone}} /span view wx:if="{{i !==0 }}" span bindtap="setDefault" id="{{i}}" 默认 /span /view /view /span /view /li li id="iphone{{i}}" wx:if="{{item.updateSgin}}" view view span 手机 /span span view wx:if="{{phoneWay}}" input type="tel" data-index="{{i}}" value="{{item.custPhone}}" bindinput="doCustPhone" maxlength="11" placeholder="请输入手机"/ /view view wx:if="{{!phoneWay}}" input type="tel" maxlength="4" placeholder="区号" value=""/ view - /view input type="tel" maxlength="8" placeholder="电话号码" value=""/ /view view wx:if="{{phoneWay}}" bindtap='phoneWayShow' 固话 /view view wx:if="{{!phoneWay}}" bindtap='phoneWayShow' 手机 /view view bindtap='delAddShow' data-index="{{i}}" span 删除 /span /view /span /view /view /li /block /ol view data-ac="active" id="add-phone" bindtap='addPhoneShow' image src='../../images/icon/customer-icons.png' /image 添加电话 /view /li