gpt4 book ai didi

javascript - 在 JavaScript 中输入计时器

转载 作者:行者123 更新时间:2023-12-03 11:56:47 27 4
gpt4 key购买 nike

您好,我创建了以下超时函数,该函数在用户完成输入后 2 秒或按 Enter 键时运行。它按描述工作,但由于某种原因我得到了重复的功能。例如,如果我输入 5 个字母并等待 5 2 秒,我会在两秒后收到 5 个警报。我只想收到 1 个警报。我需要改变什么?

function doSearch()
{

//run js function half a second after typing has stopped
var typingTimer; //timer identifier
var doneTypingInterval = 2000;

$(document).keypress(function(e){
$('#txtSearch').keypress(function(e){
if(e.keyCode == 13)
{
clearTimeout(typingTimer);
alert("pressesd");
}
});


//on keyup, start the countdown
$('#txtSearch').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});


//user is "finished typing," do somethin
function doneTyping()
{
alert("done");
clearTimeout(typingTimer);
}


}

提前致谢

最佳答案

您的脚本中有几个语法错误。修改后的代码:

var typingTimer;  //timer identifier

function doSearch()
{

//run js function half a second after typing has stopped
var doneTypingInterval = 2000;

//on keyup, start the countdown
$('#txtSearch').keyup(function(e){
if(e.keyCode == 13)
{
clearTimeout(typingTimer);
alert("pressesd");
}
else
{
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
}

//user is "finished typing," do somethin
function doneTyping()
{
alert("done");
clearTimeout(typingTimer);
}

工作 fiddle here .

编辑了 fiddle ,现在它确实有效:/

关于javascript - 在 JavaScript 中输入计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25580586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com