[英]Set delay within event
我的代碼-
hits.on('rowSelected', function (evt) {
setTimeout(function() { alert('hi'); }, 5000);
});
所以我有一個hits
表。 在該表中選擇一行時,將觸發此事件。 問題是我希望5秒鍾不能再次選擇一行。 IMO,這不起作用,因為每次選擇一行時都會觸發表上的事件,而沒有給setTimeout
時間延遲。
有沒有更好的辦法?
我建議使用變量來存儲是否已單擊元素。
在if
條件中運行setTimeout()
,以檢查此變量。 單擊元素后,請更新變量,以使其不再被單擊。 然后,一旦超時解決,請再次啟用單擊。
可以在以下內容中看到:
var hits = $("p"); var clickable = true; // It's clickable by default hits.on('click', function(evt) { if (clickable) { // Check whether it can be clicked clickable = false; // Once clicked, don't allow further clicks setTimeout(function() { alert('hi'); clickable = true; // Make it clickable again }, 5000); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Click this paragraph.</p>
希望這可以幫助! :)
下面是我能想到的最優雅的解決方案,使用一個按鈕來模擬行為。
其工作方式如下:
handler
)綁定到元素,並使用jQuery的one()
僅執行一次。 setTimeout()
等待5秒鍾,然后重新綁定事件處理程序以進行下一次執行。 let button = $('#button'); button.one('click', function handler() { console.log('clicked'); // handle event here setTimeout(() => $(this).one('click', handler), 5000); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Click me!</button>
這種方法具有以下優點:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.