問題描述
我想在用戶輸入完文本框后觸發 ajax 請求.我不希望它在每次用戶輸入字母時都運行該函數,因為這會導致大量的 ajax 請求,但我也不希望他們必須點擊 enter 按鈕.
I want to trigger an ajax request when the user has finished typing in a text box. I don't want it to run the function on every time the user types a letter because that would result in A LOT of ajax requests, however I don't want them to have to hit the enter button either.
有沒有辦法讓我可以檢測到用戶何時完成輸入然后執行 ajax 請求?
Is there a way so I can detect when the user has finished typing and then do the ajax request?
在這里使用 jQuery!戴夫
Using jQuery here! Dave
推薦答案
所以,我猜想完成輸入意味著你只需停一會兒,比如 5 秒.因此,考慮到這一點,讓我們在用戶釋放一個鍵時啟動一個計時器,并在他們按下一個鍵時清除它.我決定有問題的輸入是#myInput.
So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, lets start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.
做一些假設......
Making a few assumptions...
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var $input = $('#myInput');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
這篇關于當用戶完成輸入而不是按鍵時運行javascript函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!