說明小程序
最近在學小程序,遇到長按圖片刪除的問題,特此記錄,記錄本身的成長軌跡bash
需求: 長按刪除指定圖片markdown
須要解決的問題this
解決辦法spa
長按事件是用bindlongpress(不會跟點擊事件bindtap衝突);3d
在wxml中添加索引index,而後在js中用currentTarget.dataset.index獲取當前元素下標code
經過splice方法刪除splice(index,1),刪除一個當前元素orm
具體實現xml
<view class="uploader__files"> <block wx:for="{{images}}" wx:key="{{item.id}}" > <view class="uploader__file" bindlongpress="deleteImage" data-index="{{index}}"> <image mode="aspectFill" class="uploader__img" src="{{item.path}}" /> </view> </block> </view> 複製代碼
在wxml中添加 bindlongpress="deleteImage" data-index="{{index}}" 來綁定事件並添加索引index索引
deleteImage: function (e) { var that = this; var images = that.data.images; var index = e.currentTarget.dataset.index;//獲取當前長按圖片下標 wx.showModal({ title: '提示', content: '肯定要刪除此圖片嗎?', success: function (res) { if (res.confirm) { console.log('點擊肯定了'); images.splice(index, 1); } else if (res.cancel) { console.log('點擊取消了'); return false; } that.setData({ images }); } }) } 複製代碼
刪除部分的代碼
注意currentTarget與target的區別
效果展現