这次给大家带来如何实现在微信小程序中长按删除图片,实现在微信小程序中长按删除图片的注意事项有哪些,下面就是实战案例,一起来看一下。
说明
最近在学小程序,遇到长按图片删除的问题,特此记录,记录自己的成长轨迹
需求:
长按删除指定图片
需要解决的问题
长按事件如何表示出来?
如何获取当前长按元素的下标?
如何删除元素?
解决办法
长按事件是用bindlongpress(不会跟点击事件bindtap冲突);
在wxml中添加索引index,然后在js中用currenttarget.dataset.index获取当前元素下标
通过splice方法删除splice(index,1),删除一个当前元素
具体实现
<view class="uploaderfiles">
<block wx:for="{{images}}" wx:key="{{item.id}}" >
<view class="uploaderfile" bindlongpress="deleteimage" data-index="{{index}}">
<image mode="aspectfill" class="uploaderimg" 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的区别
1. currenttarget:绑定的事件当前元素及其子元素都会触发
2. target: 绑定的事件 子元素不会被触发事件
效果展示
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
如何搭建react全家桶环境
应该如何搭建webpack+react开发环境
以上就是如何实现在微信小程序中长按删除图片的详细内容。