2016-07-22 4 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

関連する問題