微信小程序动态触发点击事件
2018-10-12 本文已影响72人
肉肉要次肉
微信展示列表效果借助于 wx:for
通常我们在静态创建一个view或是button,他对应的点击事件很简单

.wxml文件代码示例:

红框里的都是每个view,对应绑定的点击方法名字,接下来,我们在.js文件中分别来实现这些对应的点击方法

那以上是静态实现点击事件,那列表的时候如何实现动态触发点击事件呢?
动态触发点击事件
给有点击事件的组件添加一个 data-any 属性,any可以是任意数据类型,any的名称可以自己任意定义
这里有一个例子:

.wxml文件代码:

这里的data-any,双引号里的值,
item:表示对象全部的值
item.xx:表示数组中某一个对象当中对应的某个数据
index:表示数组下标

在if(indf==0)这里,因为.wxml文件中,定义的是index下标,那如果改成item,就可以写成
if(indf.title=="全部订单"),或者if(indf.index ==0)这样
效果图如下:

这里,在额外的讲一下.js文件代码图片中,定义接收.wxml组件data中数据
var id = e.currentTarget.dataset.pid;
var indf = e.currentTarget.dataset.indd;
这里说一下.currentTarget和.target区别
e.currentTarget:指的是注册了事件监听器的对象
e.target:指的是该对象里的子对象,也是触发这个事件的对象