2014-01-10 67 views
3

這是...簡單的代碼(現在全局定義的變量)。第一次點擊它按預期工作......第二次如何導致事件連續發射兩次,這就是我想要的......任何想法?jQuery手機按鈕點擊處理程序發射兩次?

$(document).on("vclick", "#timer", function() { 

    console.log(past_ts); 
    if(past_ts === 0) { 
    past_ts = new Date().getTime(); 
    $(this).text("Stop Set Timer"); 
    } 
    else { 
    curr_ts = new Date().getTime(); 
    diff_ts = ((curr_ts - past_ts)/1000); 

    past_ts = 0; // Reset timer 

    $(this).text("Start Set Timer"); 

    } 
}); 
+0

你是否將代碼包裝在'pageinit'或其他事件中? – Omar

回答

5

簡單。有兩種方法可以解決這個問題。

1)使用e.stopImmediatePropagation()後打開功能(第二行)。一定要傳遞事件參數。

$(document).on("vclick", "#timer", function(e) { 
             // ^note this param 
    e.stopImmediatePropagation(); 

    console.log(past_ts); 
    if(past_ts === 0) { 
    past_ts = new Date().getTime(); 
    $(this).text("Stop Set Timer"); 
    } 
    else { 
    curr_ts = new Date().getTime(); 
    diff_ts = ((curr_ts - past_ts)/1000); 

    past_ts = 0; // Reset timer 

    $(this).text("Start Set Timer"); 

    } 
}); 

文檔可以在這裏找到:http://api.jquery.com/event.stopimmediatepropagation/

OR

2)嘗試使用off().on()技術。這確保瞭如果你已經綁定了行爲,它將解除綁定,然後重新綁定。

$(document).off("vclick", "#timer").on("vclick", "#timer", function() { 

    console.log(past_ts); 
    if(past_ts === 0) { 
    past_ts = new Date().getTime(); 
    $(this).text("Stop Set Timer"); 
    } 
    else { 
    curr_ts = new Date().getTime(); 
    diff_ts = ((curr_ts - past_ts)/1000); 

    past_ts = 0; // Reset timer 

    $(this).text("Start Set Timer"); 

    } 
}); 
+0

完美...它像一個魅力,但爲什麼我需要這樣做首先呢? –

+1

@ Alex.Barylski當您調用$ .on()時,您將一個事件綁定到該ID。每次連續調用$ .on()時,都會添加重複的綁定(即多個綁定)。通過使用e.stopImmediatePropagation(),它會檢測到已經分配了一個綁定並阻止它再次被添加。 –

+0

好的,我把它改爲$(「#timer」)。click(function(e)...這似乎仍然是必需的......無論如何,它的工作非常好,謝謝:)現在有什麼方法可以鎖定屏幕,除非按下「停止」按鈕:p –