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

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

在这里使用jQuery !


当前回答

如果您正在寻找特定的长度(例如邮政编码字段):

$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
        //make ajax request here after.
    }
  });

其他回答

哇,甚至有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);      
});

上面选择的答案不成立。

因为typingTimer偶尔会设置多次(对于快速键入者,按下键之前按下键两次),那么它就不能正确清除。

下面的解决方案解决了这个问题,并将在完成OP请求后调用X秒。它也不再需要冗余的keydown函数。我还添加了一个检查,这样如果输入为空,函数调用就不会发生。

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

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

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

和相同的代码在普通JavaScript解决方案:

//setup before functions
let typingTimer;                //timer identifier
let doneTypingInterval = 5000;  //time in ms (5 seconds)
let myInput = document.getElementById('myInput');

//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

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

这个解决方案确实使用了ES6,但在这里没有必要。只需将let替换为var,将箭头函数替换为常规函数。

是的,你可以在每个key up事件上设置一个超时,比如2秒,它会触发一个ajax请求。您还可以存储XHR方法,并在随后的按键事件中中止它,这样可以节省更多的带宽。下面是我为自己的自动完成脚本写的一些东西。

var timer;
var x;

$(".some-input").keyup(function () {
    if (x) { x.abort() } // If there is an existing XHR, abort it.
    clearTimeout(timer); // Clear the timer so we don't end up with dupes.
    timer = setTimeout(function() { // assign timer a new timeout 
        x = $.getJSON(...); // run ajax request and store in x variable (so we can cancel)
    }, 2000); // 2000ms delay, tweak for faster/slower
});

希望这能有所帮助,

马可

为什么不直接使用onfocusout?

https://www.w3schools.com/jsreF/event_onfocusout.asp

如果它是一个表单,它们将始终保留每个输入字段的焦点,以便单击提交按钮,这样您就知道没有输入会错过调用其onfocusout事件处理程序。

下面是一个解决方案,它在不输入1秒后触发,但在输入为空白时也会立即触发。这在用户删除输入查询后清除搜索结果时非常有用。此解决方案还支持复制和粘贴到搜索框中。$(() =>{…});在简单的Jquery术语中,包装代码的顶部部分仅仅意味着“在页面加载时执行此操作”。

var searchTimer;
var searchInterval = 1000;

$(() => {
    $('#search-box').on('input', (event) => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            searchContacts(event.target.value);
        }, (event.target.value.length > 0) ? searchInterval : 0);
    });
});

function searchContacts(val) {
    console.log('searching: ' + val);
}