gpt4 book ai didi

javascript - 检查输入在一段时间后是否没有改变(稳定)

转载 作者:行者123 更新时间:2023-12-02 17:15:00 28 4
gpt4 key购买 nike

如果输入稳定,我想触发 AJAX 请求(以便不在每个新字符后发送请求)。我尝试了以下方法:

$('#input').keyup(function(){

// Get the value when keyup is fired
value = $('#input').val();

setTimeout(function(){

// If new value after 1 second is the same that the previous value
if( value == $('#input').val() ){
do_stuff();
}

}, 1000); // Wait 1 second to stabilize

});

但我最终得到了一个等待 1 秒稳定的脚本,然后多次触发请求,而不仅仅是一次。

您有更好的脚本的想法吗,或者也许有一个 jQuery 方法可以做到这一点?

谢谢

最佳答案

如果用户再次输入如下文本,则必须清除超时:

    var Timeout; // initialize a variable
$(document).ready(function () {
$('input#input').keypress(function () {
var txtbox = $(this); // copy of this object for further usage

if (Timeout) //check if timeout not null
clearTimeout(Timeout); // not null so clear it
Timeout = setTimeout(function () { // set timeout for 1 second
alert(txtbox.val());
}, 1000);
});
});

FIDDLE DEMO

关于javascript - 检查输入在一段时间后是否没有改变(稳定),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24511696/

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