小程序模板網(wǎng)

小程序?qū)崿F(xiàn)長(zhǎng)按刪除圖片

發(fā)布時(shí)間:2018-05-30 11:40 所屬欄目:小程序開(kāi)發(fā)教程
  • 說(shuō)明

    最近在學(xué)小程序,遇到長(zhǎng)按圖片刪除的問(wèn)題,特此記錄,記錄自己的成長(zhǎng)軌跡

  • 需求: 長(zhǎng)按刪除指定圖片

  • 需要解決的問(wèn)題

    1. 長(zhǎng)按事件如何表示出來(lái)?
    2. 如何獲取當(dāng)前長(zhǎng)按元素的下標(biāo)?
    3. 如何刪除元素?
  • 解決辦法

    1. 長(zhǎng)按事件是用bindlongpress(不會(huì)跟點(diǎn)擊事件bindtap沖突);

    2. 在wxml中添加索引index,然后在js中用currentTarget.dataset.index獲取當(dāng)前元素下標(biāo)

    3. 通過(guò)splice方法刪除splice(index,1),刪除一個(gè)當(dāng)前元素

  • 具體實(shí)現(xiàn)

<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}}" 來(lái)綁定事件并添加索引index

deleteImage: function (e) {
    var that = this;
    var images = that.data.images;
    var index = e.currentTarget.dataset.index;//獲取當(dāng)前長(zhǎng)按圖片下標(biāo)
    wx.showModal({
      title: '提示',
      content: '確定要?jiǎng)h除此圖片嗎?',
      success: function (res) {
        if (res.confirm) {
          console.log('點(diǎn)擊確定了');
          images.splice(index, 1);
        } else if (res.cancel) {
           console.log('點(diǎn)擊取消了');
           return false;       
          }
        that.setData({
          images
        });
      }
    })
  }

刪除部分的代碼

  • 注意currentTarget與target的區(qū)別

    1. currentTarget:綁定的事件當(dāng)前元素及其子元素都會(huì)觸發(fā)
    2. target: 綁定的事件 子元素不會(huì)被觸發(fā)事件
  • 效果展示


本文地址:http://m.u-renovate.com/wxmini/doc/course/24492.html 復(fù)制鏈接 如需定制請(qǐng)聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢
AI智能客服 ×