小程序事件处理
<!--pages/06_learn_event/index.wxml--> <!-- 1.事件的基本使用 --> <button bindtap="onBtnTap">按钮</button> <!-- 2.event中target和currentTarget区别 --> <view id="outer" class="outer" data-name="why" bindtap="onOuterViewTap"> <view id="inner" class="inner"></view> </view> <!-- 3.event中touches和changeTouches区别 --> <view class="touches" bindtap="onTouchTap" bindlongpress="onLongPress" bindtouchend="onTouchEnd" > 多指触摸 </view> <!-- 4.event的参数传递 --> <view class="arguments" bindtap="onArgumentsTap" data-name="why" data-age="18" data-height="1.88" > 参数传递 </view> <!-- 5.tab-control案例(重要) --> <view class="tab-control"> <block wx:for="{{ titles }}" wx:key="*this"> <view class="item {{index === currentIndex ? 'active': ''}}" bindtap="onItemTap" data-index="{{index}}" > <text class="title">{{ item }}</text> </view> </block> </view> <!-- 6.捕获和冒泡阶段 --> <view class="view1" capture-bindtap="onView1CaptureTap" bindtap="onView1Tap"> <view class="view2" capture-bindtap="onView2CaptureTap" bindtap="onView2Tap"> <view class="view3" capture-bindtap="onView3CaptureTap" bindtap="onView3Tap"></view> </view> </view> <!-- 7.将bind替换为catch: 阻止事件仅一步传递(了解) --> <!-- 8.给逻辑传递数据, 另外一种方式: mark --> <view class="mark" bindtap="onMarkTap" data-name="why" data-age="18" mark:name="kobe" mark:age="30" > <text mark:address="洛杉矶" class="title">mark</text> </view>
// pages/06_learn_event/index.js Page({ data: { titles: ["手机", "电脑", "iPad", "相机"], currentIndex: 0 }, onItemTap(event) { const currentIndex = event.currentTarget.dataset.index console.log(currentIndex); this.setData({ currentIndex }) }, // 绑定事件监听函数 onBtnTap(event) { console.log("onBtnTap:", event); }, onOuterViewTap(event) { // 1.target触发事件的元素 // 2.currentTarget处理事件的元素 console.log("onOuterViewTap:", event); console.log(event.target); console.log(event.currentTarget); // 3.获取自定义属性: name const name = event.currentTarget.dataset.name console.log(name); }, // 监听触摸事件 onTouchTap(event) { console.log("tap:", event); }, onLongPress(event) { console.log("long:", event); }, onTouchEnd(event) { console.log("end:", event); }, // 监听事件, 并且传递参数 onArgumentsTap(event) { console.log("onArgumentsTap:", event); const { name, age, height } = event.currentTarget.dataset console.log(name, age, height); }, // 捕获和冒泡过程 onView1CaptureTap() { console.log("onView1CaptureTap"); }, onView2CaptureTap() { console.log("onView2CaptureTap"); }, onView3CaptureTap() { console.log("onView3CaptureTap"); }, onView1Tap() { console.log("onView1Tap"); }, onView2Tap() { console.log("onView2Tap"); }, onView3Tap() { console.log("onView3Tap"); }, // mark的数据传递 onMarkTap(event) { console.log(event); const data1 = event.target.dataset console.log(data1); const data2 = event.mark console.log(data2); } })
本文来自博客园,作者:杨建鑫,转载请注明原文链接:https://www.cnblogs.com/qd-lbxx/p/16665165.html