嗨,再次大師的網絡:) 現在,我有一個新的愚蠢的問題,我要求原諒我。我到處閱讀這個解決方案,但沒有找到適用於我的解決方案。OnKeyUp JavaScript時間延遲?
我有:
<input name="domain" type="text" id="domain" onKeyUp="javascript:chk_me();">
所有我問的是如何讓一個按鈕按下後,這個不檢查,但後說1000毫秒鍵盤閒置?
嗨,再次大師的網絡:) 現在,我有一個新的愚蠢的問題,我要求原諒我。我到處閱讀這個解決方案,但沒有找到適用於我的解決方案。OnKeyUp JavaScript時間延遲?
我有:
<input name="domain" type="text" id="domain" onKeyUp="javascript:chk_me();">
所有我問的是如何讓一個按鈕按下後,這個不檢查,但後說1000毫秒鍵盤閒置?
試試這個:每一個鍵被按下時
var timer;
function chk_me(){
clearTimeout(timer);
timer=setTimeout(function validate(){...},1000);
}
這樣,超時將被刪除和集合再次。
的setTimeout()將是一個;)
<input name="domain" type="text" id="domain" onKeyUp="setTimeout('chk_me()',1000);">
另一種方法,沒有全局:
var typewatch = function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
}
}();
用法:
附加事件通過JavaScript:
window.onload = function() {
document.getElementById('domain').onkeyup = function() {
typewatch(function(){alert('Time elapsed!');}, 1000);
};
};
或使用內聯事件處理程序(與其說推薦),如你在你的例子:
<input type="text" name="domain" id="domain"
onKeyUp="typewatch(function(){alert('Time elapsed!');}, 1000);"/>
試試演示here。
是什麼讓你覺得typewatch不是全球性的? – 2009-09-04 22:45:05
是typewatch是全局的,但我的意思是說,** timer **變量不在全局範圍內,並且只能由typewatch函數訪問。 – CMS 2009-09-04 22:48:33
真的很有用的帖子!
沒有全局的另一種方法,使用功能性:
function chk_me(){
if(typeof timer !== undefined){
clearTimeout(this.timer);
}
this.timer=setTimeout(function validate(){validate(...)},1000);
}
我認爲'var定時器'需要在功能體外 – Rodrigo 2009-09-04 22:17:19
你是正確的定時器必須設置功能外,我已經編輯答案 – mck89 2009-09-04 22:18:23
謝謝!這個地段的最佳答案是公平的。 – Shog9 2009-09-04 22:22:30