tap 事件会触发两次问题

 

  因项目中使用 coffeeScript (http://coffee-script.org/),此处记录下用 coffeeScript 语法解决 tap 事件触发两次的问题。javascript

 

在 id="button" 上绑定 tap 触摸事件以下代码:html

$(document).on 'tap', '#button', ()->
    # 业务逻辑代码
  console.log(111)

 

分析:

  在浏览器中点击一次 button 会输出两次 ‘111’,手机上测试偶尔输出一次,偶尔两次,非常奇怪,一开始怀疑是事件冒泡或者是默认行为,依次尝试:java

一、防止冒泡和捕获
w3c的方法是e.stopPropagation(),IE则是使用e.cancelBubble = true
由于是在微信端使用,因此不考虑 IE,在代码中加入e.stopPropagation(),111 输出偶尔一次,偶尔两次。

二、阻止默认行为
w3c的方法是e.preventDefault(),IE则是使用e.returnValue = false; 加入 preventDefault() ,111 输出两次,说明无效

w3c的方法是e.preventDefault(),IE则是使用e.returnValue = false; 加入 preventDefault() ,111 输出两次,说明无效

解决:

两种方法都不能确保触发一次,因此采用比较生硬的方法:setTimeout 延迟 200s 阻止事件再次执行:浏览器

flag = true
$(document).on 'tap', '#button', ()->
    # 业务逻辑代码
    if flag
       setTimeout(() ->
       console.log(111)
           flag = true
       , 200)
    flag = false

  

正常 js 写法:微信

var flag = true
$("#button").on("tap",function(){
 if (flag){
       setTimeout(function () {
       console.log(111)
           flag = true
       }, 200)
  }
   flag = false
})
相关文章
相关标签/搜索