因項目中使用 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 })