当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。

是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?

在这里使用jQuery !


当前回答

哇,甚至有3条评论都是正确的!

Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect .on ('input', function() { ... }); should be used to trigger keyup, paste and change events definitely .val() or .value must be used You can use $(this) inside event function instead of #id to work with multiple inputs (my decision) I use anonymous function instead of doneTyping in setTimeout to easily access $(this) from n.4, but you need to save it first like var $currentInput = $(this);

编辑我看到有些人不理解没有复制粘贴就绪代码的指示。在这里你

var typingTimer;
//                  2
$("#myinput").on('input', function () {
    //             4     3
    var input = $(this).val();
    clearTimeout(typingTimer);
    //                           5
    typingTimer = setTimeout(function() {
        // do something with input
        alert(input);
    }, 5000);      
});

其他回答

用于将参数与ES6语法一起传递给函数。

$(document).ready(() => {
    let timer = null;
     $('.classSelector').keydown(() => {
     clearTimeout(timer); 
     timer = setTimeout(() => foo('params'), 500);
  });
});

const foo = (params) => {
  console.log(`In foo ${params}`);
}

你可以使用onblur事件来检测文本框何时失去焦点: https://developer.mozilla.org/en/DOM/element.onblur

这与“停止输入”不一样,如果你关心用户输入了一堆东西,然后坐在那里,文本框仍然聚焦。

为此,我建议将setTimeout绑定到onclick事件,并假设在x段时间内没有击键,用户已经停止输入。

我觉得解决方案有点简单的输入事件:

var typingTimer;
var doneTypingInterval = 500;

$("#myInput").on("input", function () {
    window.clearTimeout(typingTimer);
    typingTimer = window.setTimeout(doneTyping, doneTypingInterval);
});

function doneTyping () {
    // code here
}

我喜欢Surreal Dream的答案,但我发现我的“doneTyping”函数会在每次按键时触发,即如果你快速输入“Hello”;当您停止输入时,该函数将触发5次,而不是只触发一次。

问题是javascript的setTimeout函数似乎不会覆盖或杀死任何旧的超时设置,但如果你自己做它工作!因此,如果设置了typingTimer,我只是在setTimeout之前添加了一个clearTimeout调用。见下文:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example

//on keyup, start the countdown
$('#myInput').on("keyup", function(){
    if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#myInput').on("keydown", function(){
    clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

注意:我本来想把这句话作为对Surreal Dream的回答的评论,但我是一个新用户,没有足够的声誉。对不起!

它只是一行下划线。js debounce函数:

$('#my-input-box').keyup(_.debounce(doSomething , 500));

这基本上是在我停止输入500毫秒后做某事。

欲了解更多信息:http://underscorejs.org/#debounce