小程序開發中遇到點擊某個組件需要得到當前點擊圖片的某些屬性,如當前的位置或者圖片鏈接,此時就可以通過自定義屬性來獲取。
1. 定義
自定義屬性的標識 data-attrName ,其中後面的“attrName”爲隨意命名,前綴“data-”是必須的。
2. 使用
在wxml文件中增加類似如下代碼:
<image class="image-style" data-src='{{imgSrc}}' src="{{imgSrc}}" bindtap="previewImage"></image>
然後在預覽界面就可以如下展示:
// 預覽圖片
previewImage: function(e) {
var current = e.target.dataset.src;
wx.previewImage({
current: current, // 當前顯示圖片的http鏈接
urls: this.data.imgList // 需要預覽的圖片http鏈接列表
})
},
3. e.target 與 e.currentTarget
e.target 拿的是點擊的對象的屬性;
如果是 data- 放到外層了,點擊裏面的元素是拿不到屬性值的;
而用 e.currentTarget 則是拿 bintap/catchtap 所在的對象的屬性~,點擊裏面的元素一樣能拿到屬性值 。
<view class='a-child' data-tid='{{child.ID}}' bindtap='selectChild'>
<image class='avatar' src='../../images/localImages/default_user.png'></image>
<view class='child-mid'>
<view class='mid-top child-name'>{{child.STUDENTNAME}}</view>
</view>
</view>
示例中 要拿 tid 要如下:
selectChild: function(e) {
//獲取ID
var tid = e.currentTarget.dataset.tid
console.log('tid: ' + tid)
},