想要通过事件冒泡,获取到.item的data,WXML如下:

<view class="toolbar" catchtouchend="format">
    <view class="item" data-name="list" data-value="ordered">
      <text class="iconfont icon-youxuliebiao"></text>
      <text class="name">有序列表</text>
    </view>
</view>

上面的结构是无法在js中通过e.target.dataset获取到data-namedata-value的:

format(e){
    console.log(e.target.dataset);  // {}
}

原因很简单,产生事件的是.item的子元素,并不是.item元素

所以,要想获得data数据,.item就不能有子元素:

<view class="toolbar" catchtouchend="format">
    <view class="item" data-name="list" data-value="ordered">
        有序列表
    </view>
</view>


...
format(e) {
    console.log(e.target.dataset);  // {name: "list", value: "ordered"}
}
...

经过尝试,用text代替view,也是可以正常获取的,并且里面还能有子元素:

<view class="toolbar" catchtouchend="format">
    <text class="item" data-name="list" data-value="ordered">
        <text class="iconfont icon-youxuliebiao"></text>
        <text class="name">有序列表</text>
    </text>
</view>

但要注意,text组件里面只能嵌套text,其他标签是无法正常显示的。

End

标签: 微信小程序, 事件冒泡