微信小程序bindtap事件與冒泡阻止詳解
bindtap就是點擊事件
在.wxml文件綁定:
<text id='textId' data-userxxx='100' bindtap='tapMessage'>cilck here</text>
在一個組件的屬性上添加bindtap并賦予一個值(一個函數(shù)名)
當點擊該組件時, 會觸發(fā)相應的函數(shù)執(zhí)行
在后臺.js文件中定義tapMessage函數(shù):
//index.js
Page({
data: {
mo: 'Hello World!!',
userid : '1234',
},
// 定義函數(shù)
tapMessage: function(event) {
console.log(event.target.id); // 可獲得
console.log(event.target.name); // 無法獲得, 通過target只能直接獲取id
console.log(event.target.dataset); // 要獲得其它屬性, 需要從dataset(數(shù)據(jù)集)中獲取
console.log(event.target.dataset.userxxx); // userxxx為自定義的屬性名, 但命名方式為:data-userxxx
// 這里還原使用userXxx
console.log(event.target.dataset.userXxx);
}
})
event封裝的是該事件的信息, 如上通過它可得到一些數(shù)據(jù)
注意一點:
<!-- data-userXxx,這個大寫的X要改為-x -->
<text id='textId' data-user-xxx='100' bindtap='tapMessage'>cilck here</text>
自定義數(shù)據(jù)(data-)中的大寫改為 短橫線+其小寫
取數(shù)據(jù)時, 去掉data和那些短橫線并還原大寫 (data-user-xxx --> userXxx)
事件冒泡就是指嵌套事件發(fā)生
如果多層標簽嵌套, 里層事件發(fā)生后, 其外層會相應發(fā)生, 如:
<view bindtap='handout'> outer <view bindtap='handmiddle'> middle <view bindtap='handinner'>inner</view> </view> </view>
handout: function () {
console.log("out");
},
handmiddle: function () {
console.log("middle");
},
handinner: function () {
console.log("inner");
}
點擊inner三個事件都執(zhí)行, 點擊middlek執(zhí)行handmiddle和handout, 點擊out只執(zhí)行handout
阻止事件冒泡行為: 將bindtap改為catchtap就行了, 只會觸發(fā)自身的點擊事件
<view bindtap='handout'> outer <view catchtap='handmiddle'> middle <view bindtap='handinner'>inner</view> </view> </view>
需要理解是, 它阻斷自身的冒泡行為
如上點擊inner, 執(zhí)行的是handinner和handmiddle兩個函數(shù)
不管是不是自身觸發(fā)的點擊行為, 傳到我這里, 我就將它阻斷(不再向上傳遞)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
用JS實現(xiàn)網(wǎng)頁元素陰影效果的研究總結
用JS實現(xiàn)網(wǎng)頁元素陰影效果的研究總結...2007-08-08
跟我學習javascript的for循環(huán)和for...in循環(huán)
跟我學習javascript的for循環(huán)和for...in循環(huán),它們是JavaScript中提供了兩種方式迭代對象,本文就和大家一起學習for循環(huán)和for...in循環(huán),感興趣的小伙伴們可以參考一下2015-11-11
getElementByIdx_x js自定義getElementById函數(shù)
最近看JS代碼,發(fā)現(xiàn)不少人問getElementByIdx_x是什么函數(shù),其實就是個getElementById自定義函數(shù)2012-01-01

