2016-07-22 79 views
3

我已經添加了一段代碼,我想要在評論中實現。jquery延遲點擊後,允許不同的選擇

有9個按鈕,我需要點擊按鈕的數據ID值,但用戶可以點擊一個按鈕,然後快速決定他們想單擊一個不同的按鈕,所以我想要的值點擊最後一個按鈕。

$('#add-shot a.btn').on('click', function(e) { 
    e.preventDefault(); 

    // delay for 1500 
    // if no other button is clicked, then simply use $(this).data('id'); 
    // else, 
    // if other button is clicked, don't use original data-id but use the new data-id 

    var id = $(this).data('id'); 
    // run the rest of the code 

}); 

回答

4

您可以使用全球定時器setTimeout()。每次點擊只需清除超時,如果他們沒有被點擊1.5秒內,則匿名函數將被調用並獲得相應id

var timer; 
 

 
$('button').on('click', function(e) { 
 
    e.preventDefault(); 
 
    var self = this; 
 
    clearTimeout(timer);    // Reset the timer. 
 
    timer = setTimeout(function(){  // Call this function if the timer 
 
    \t var id = $(self).data('id'); // did not reset within 1.5 seconds. 
 
     alert(id); 
 
    }, 1500); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<button data-id="foo"> 
 
foo 
 
</button> 
 
<button data-id="bar"> 
 
bar 
 
</button> 
 
<button data-id="biz"> 
 
biz 
 
</button>

+0

運行完美,謝謝 – user537137