I want the ajax to executed when user stops typing but this it isn't working on key up event and when I am putting onkeyup=doneTyping() in input with id searchtext the browser is crashing
我希望在用户停止输入时执行ajax,但是它不能处理key up事件,当我在输入时使用id searchtext将onkeyup = doneTyping()放入浏览器时崩溃
<script>
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var $input = $('#search_text');
var txt = $(this).val();
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
function doneTyping () {
$.ajax({
url:"fetch.php",
method:"post",
data:{search:txt},
dataType:"text",
success:function(data)
{
$('#searchresults').html(data);
}
});
//do something
}
</script>
Thank you
1 个解决方案
#1
0
I turned your code into a snippet and added some console logging to show what is going on.
我将您的代码转换为代码段,并添加了一些控制台日志记录以显示正在发生的事情。
This shows that the events are working exactly as you describe ... and 'Done typing' shows in the console 5 seconds after I quit typing.
这表明事件正如您描述的那样工作...并且在我退出键入后5秒钟在控制台中显示“完成输入”。
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var $input = $('#search_text');
console.log("$input = ", $input.length);
$input.on('keyup', function() {
console.log("Key up");
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
$input.on('keydown', function() {
console.log("Key down");
clearTimeout(typingTimer);
});
function doneTyping() {
console.log("Done typing");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
Test input: <input id="search_text">
#1
0
I turned your code into a snippet and added some console logging to show what is going on.
我将您的代码转换为代码段,并添加了一些控制台日志记录以显示正在发生的事情。
This shows that the events are working exactly as you describe ... and 'Done typing' shows in the console 5 seconds after I quit typing.
这表明事件正如您描述的那样工作...并且在我退出键入后5秒钟在控制台中显示“完成输入”。
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var $input = $('#search_text');
console.log("$input = ", $input.length);
$input.on('keyup', function() {
console.log("Key up");
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
$input.on('keydown', function() {
console.log("Key down");
clearTimeout(typingTimer);
});
function doneTyping() {
console.log("Done typing");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
Test input: <input id="search_text">