简体   繁体   English

当用户完成键入而不是按键时运行 javascript function?

[英]Run javascript function when user finishes typing instead of on key up?

I want to trigger an ajax request when the user has finished typing in a text box.当用户在文本框中输入完毕时,我想触发 ajax 请求。 I don't want it to run the function on every time the user types a letter because that would result in A LOT of ajax requests, however I don't want them to have to hit the enter button either.我不希望它在每次用户键入字母时运行 function,因为这会导致很多 ajax 请求,但是我也不希望他们必须按下回车按钮。

Is there a way so I can detect when the user has finished typing and then do the ajax request?有没有一种方法可以检测用户何时完成输入,然后执行 ajax 请求?

Using jQuery here!在这里使用 jQuery!

So, I'm going to guess finish typing means you just stop for a while, say 5 seconds.所以,我猜想完成打字意味着你只是停下来一会儿,比如 5 秒。 So with that in mind, let's start a timer when the user releases a key and clear it when they press one.因此,考虑到这一点,让我们在用户释放一个键时启动一个计时器,并在他们按下一个键时清除它。 I decided the input in question will be #myInput.我决定有问题的输入将是#myInput。

Making a few assumptions...做几个假设...

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 seconds for example
var $input = $('#myInput');

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

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

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

The chosen answer above does not work.上面选择的答案不起作用。

Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.因为 typingTimer 偶尔会设置多次(在快速打字机等触发 keydown 之前按下两次 keyup),所以它不能正确清除。

The solution below solves this problem and will call X seconds after finished as the OP requested.下面的解决方案解决了这个问题,并在完成后按照 OP 的要求调用 X 秒。 It also no longer requires the redundant keydown function.它也不再需要多余的 keydown 功能。 I have also added a check so that your function call won't happen if your input is empty.我还添加了一个检查,以便在您的输入为空时不会发生您的函数调用。

//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
}

And the same code in vanilla JavaScript solution:以及 vanilla 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
}

This solution does use ES6 but it's not necessary here.这个解决方案确实使用了 ES6,但这里没有必要。 Just replace let with var and the arrow function with a regular function.只需将let替换为var并将箭头函数替换为常规函数即可。

It's just one line with underscore.js debounce function:这只是带有underscore.js debounce 功能的一行

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

This basically says doSomething 500 milliseconds after I stop typing.这基本上是在我停止输入 500 毫秒后表示doSomething

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

Late answer but I'm adding it because it's 2019 and this is entirely achievable using pretty ES6, no third party libraries, and I find most of the highly rated answers are bulky and weighed down with too many variables.迟到的答案,但我添加它是因为它是 2019 年,这完全可以使用漂亮的 ES6 来实现,没有第三方库,而且我发现大多数高度评价的答案都很笨重,而且变量太多。

Elegant solution taken from this excellent blog post.优雅的解决方案取自这篇出色的博客文章。

function debounce(callback, wait) {
  let timeout;
  return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(function () { callback.apply(this, args); }, wait);
  };
}

window.addEventListener('keyup', debounce( () => {
    // code you would like to run 1000ms after the keyup event has stopped firing
    // further keyup events reset the timer, as expected
}, 1000))

Yes, you can set a timeout of say 2 seconds on each and every key up event which will fire an ajax request.是的,您可以在每个触发 ajax 请求的按键事件上设置 2 秒的超时时间。 You can also store the XHR method and abort it on subsequent key press events so that you save bandwith even more.您还可以存储 XHR 方法并在随后的按键事件中中止它,以便您节省更多带宽。 Here's something I've written for an autocomplete script of mine.这是我为我的自动完成脚本编写的内容。

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
});

Hope this helps,希望这可以帮助,

Marko马尔科

var timer;
var timeout = 1000;

$('#in').keyup(function(){
    clearTimeout(timer);
    if ($('#in').val) {
        timer = setTimeout(function(){
            //do stuff here e.g ajax call etc....
             var v = $("#in").val();
             $("#out").html(v);
        }, timeout);
    }
});

full example here: http://jsfiddle.net/ZYXp4/8/完整示例:http: //jsfiddle.net/ZYXp4/8/

Both top 2 answers doesn't work for me.前 2 个答案对我都不起作用。 So, here is my solution:所以,这是我的解决方案:

var timeout = null;

$('#myInput').keyup(function() {
    clearTimeout(timeout);

    timeout = setTimeout(function() {
        //do stuff here
    }, 500);
});

Modifying the accepted answer to handle additional cases such as paste:修改接受的答案以处理其他情况,例如粘贴:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 2000;  //time in ms, 2 second for example
var $input = $('#myInput');

// updated events 
$input.on('input propertychange paste', function () {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);      
});

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

Declare the following delay function:声明以下delay函数:

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})()

and then use it:然后使用它:

let $filter = $('#item-filter');
$filter.on('keydown', function () {
    delay(function () {            
        console.log('this will hit, once user has not typed for 1 second');            
    }, 1000);
});    

I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, ie if you type "Hello" really quickly;我喜欢超现实梦的回答,但我发现我的“doneTyping”功能会在每次按键时触发,即如果你真的很快输入“Hello”; instead of firing just once when you stop typing, the function would fire 5 times.当您停止输入时,该函数不会只触发一次,而是会触发 5 次。

The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works!问题是 javascript setTimeout 函数似乎不会覆盖或终止已设置的任何旧超时,但如果您自己执行它,它会起作用! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set.因此,如果设置了 typingTimer,我只是在 setTimeout 之前添加了一个 clearTimeout 调用。 See below:见下文:

//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
}

NB I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation.注意,我本来希望将其添加为对超现实梦的回答的评论,但我是新用户,没有足够的声誉。 Sorry!对不起!

I don't think keyDown event is necessary in this case (please tell me why if I'm wrong).我认为在这种情况下不需要 keyDown 事件(如果我错了,请告诉我为什么)。 In my (non-jquery) script similar solution looks like that:在我的(非 jquery)脚本中,类似的解决方案如下所示:

var _timer, _timeOut = 2000; 



function _onKeyUp(e) {
    clearTimeout(_timer);
    if (e.keyCode == 13) {      // close on ENTER key
        _onCloseClick();
    } else {                    // send xhr requests
        _timer = window.setTimeout(function() {
            _onInputChange();
        }, _timeOut)
    }

}

It's my first reply on Stack Overflow, so I hope this helps someone, someday:)这是我对 Stack Overflow 的第一次回复,所以我希望有一天能对某人有所帮助:)

I was implementing the search at my listing and needed it to be ajax based.我正在我的列表中实现搜索,并且需要它基于 ajax。 That means that on every key change, searched results should be updated and displayed.这意味着在每次关键更改时,都应更新和显示搜索结果。 This results in so many ajax calls sent to server, which is not a good thing.这导致向服务器发送大量 ajax 调用,这不是一件好事。

After some working, I made an approach to ping the server when the user stops typing.经过一些工作后,我采取了一种在用户停止输入时对服务器执行 ping 操作的方法。

This solution worked for me:这个解决方案对我有用:

$(document).ready(function() {
    $('#yourtextfield').keyup(function() {
        s = $('#yourtextfield').val();
        setTimeout(function() { 
            if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
                $.ajax({
                    type: "POST",
                    url: "yoururl",
                    data: 'search=' + s,
                    cache: false,
                    beforeSend: function() {
                       // loading image
                    },
                    success: function(data) {
                        // Your response will come here
                    }
                })
            }
        }, 1000); // 1 sec delay to check.
    }); // End of  keyup function
}); // End of document.ready

You will notice that there is no need to use any timer while implementing this.您会注意到在实现此功能时无需使用任何计时器。

agree with the @going 's answer.同意@going 的回答。 Another similar solution that worked for me is the one below.另一个对我有用的类似解决方案是下面的解决方案。 The only difference is that I am using .on("input"...) instead of keyup.唯一的区别是我使用 .on("input"...) 而不是 keyup。 This only captures changes in the input.这仅捕获输入中的变化。 other keys like Ctrl, Shift etc. are ignored其他键如 Ctrl、Shift 等被忽略

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

//on input change, start the countdown

$('#myInput').on("input", function() {    
    clearTimeout(typingTimer);
    typingTimer = setTimeout(function(){
        // doSomething...
    }, doneTypingInterval);
});

I feel like the solution is somewhat a bit simpler with the input event:我觉得input事件的解决方案有点简单:

var typingTimer;
var doneTypingInterval = 500;

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

function doneTyping () {
    // code here
}

Well, strictly speaking no, as the computer cannot guess when the user has finished typing.好吧,严格来说不是,因为计算机无法猜测用户何时完成输入。 You could of course fire a timer on key up, and reset it on every subsequent key up.您当然可以在按键时触发计时器,并在每次后续按键时将其重置。 If the timer expires, the user hasn't typed for the timer duration - you could call that "finished typing".如果计时器到期,则用户在计时器持续时间内没有输入 - 你可以称之为“完成输入”。

If you expect users to make pauses while typing, there's no way to know when they are done.如果您希望用户在键入时暂停,则无法知道他们何时完成。

(Unless of course you can tell from the data when they are done) (当然,除非您可以从数据中看出它们何时完成)

I just figured out a simple code to wait for user to finish typing:我只是想出了一个简单的代码来等待用户完成输入:

step 1.set time out to null then clear the current timeout when the user is typing.步骤 1. 将超时设置为空,然后在用户键入时清除当前超时。

step 2.trigger clear timeout to the variable define before keyup event is triggered.步骤 2.trigger 在触发 keyup 事件之前清除变量定义的超时。

step 3.define timeout to the variable declared above;步骤 3.define timeout 到上面声明的变量;

<input type="text" id="input" placeholder="please type" style="padding-left:20px;"/>
<div class="data"></div>

javascript code javascript代码

var textInput = document.getElementById('input');
var textdata = document.querySelector('.data');
// Init a timeout variable to be used below
var timefired = null;

// Listen for keystroke events
// Init a timeout variable to be used below
var timefired = null;// Listen for keystroke events
textInput.onkeyup = function (event) {
clearTimeout(timefired);
timefired = setTimeout(function () {
    textdata.innerHTML = 'Input Value:'+ textInput.value;
  }, 600);
};

 const inText = document.getElementById('inText') const outText = document.getElementById('outText') const delay = 1000 let timer inText.addEventListener('input', code => { clearTimeout(timer); timer = setTimeout(x => { outText.innerHTML = inText.value }, delay, code) })
 <textarea id='inText'>edit this and...</textarea> <pre id='outText'>see the results after you stop typing for one second</pre>

This is the a simple JS code I wrote:这是我写的一个简单的 JS 代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    } 
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>

Why not just use onfocusout?为什么不直接使用 onfocusout?

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

If it's a form, they will always leave focus of every input field in order to click the submit button so you know no input will miss out on getting its onfocusout event handler called.如果它是一个表单,他们将始终离开每个输入字段的焦点,以便单击提交按钮,这样您就知道在调用其 onfocusout 事件处理程序时不会错过任何输入。

You can use the onblur event to detect when the textbox loses focus: https://developer.mozilla.org/en/DOM/element.onblur您可以使用 onblur 事件来检测文本框何时失去焦点: https ://developer.mozilla.org/en/DOM/element.onblur

That's not the same as "stops typing", if you care about the case where the user types a bunch of stuff and then sits there with the textbox still focused.这与“停止输入”不同,如果您关心用户输入一堆东西然后坐在那里文本框仍然聚焦的情况。

For that I would suggest tying a setTimeout to the onclick event, and assuming that after x amount of time with no keystrokes, the user has stopped typing.为此,我建议将 setTimeout 绑定到 onclick 事件,并假设在 x 时间后没有击键,用户已停止输入。

Multiple timers per page每页多个计时器

All the other answers only work for one control ( my other answer included).所有其他答案仅适用于一个控件(包括我的其他答案)。 If you have multiple controls per page (eg in a shopping cart) only the last control where the user typed something will get called .如果每个页面有多个控件(例如在购物车中) ,则只有最后一个用户输入内容的控件才会被调用 In my case this is certainly not the wished behaviour - each control should have its own timer.就我而言,这当然不是所希望的行为——每个控件都应该有自己的计时器。

To solve this, you simply have to pass an ID to the function and maintain a timeoutHandles dictionary as in the following code:为了解决这个问题,您只需将一个 ID 传递给函数并维护一个 timeoutHandles 字典,如下面的代码所示:

Function Declaration:函数声明:

var delayUserInput = (function () {
    var timeoutHandles = {};    
    return function (id, callback, ms) {        
        if (timeoutHandles[id]) {
            clearTimeout(timeoutHandles[id]);
        }

        timeoutHandles[id] = setTimeout(callback, ms);             
    };
})();

Function Usage:功能用法:

  delayUserInput('yourID', function () {
     //do some stuff
  }, 1000);

If there is necessity for the user to move away from the field, we can use "onBlur" instead of Onchange in Javascript如果用户有必要离开现场,我们可以在 Javascript 中使用“onBlur”而不是 Onchange

  <TextField id="outlined-basic"  variant="outlined" defaultValue={CardValue} onBlur={cardTitleFn} />

If that is not necessary setting timer would be the good option.如果没有必要设置计时器将是一个不错的选择。

If you are looking for a specific length (such as a zipcode field):如果您正在寻找特定长度(例如邮政编码字段):

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

Not sure if my needs are just kind of weird, but I needed something similar to this and this is what I ended up using:不确定我的需求是否有点奇怪,但我需要类似的东西,这就是我最终使用的:

$('input.update').bind('sync', function() {
    clearTimeout($(this).data('timer'));            
    $.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
        if(x.success != true) {
            triggerError(x.message);    
        }
    }, 'json');
}).keyup(function() {
    clearTimeout($(this).data('timer'));
    var val = $.trim($(this).val());
    if(val) {
        var $this = $(this);
        var timer = setTimeout(function() {
            $this.trigger('sync');
        }, 2000);
        $(this).data('timer', timer);
    }
}).blur(function() {
    clearTimeout($(this).data('timer'));     
    $(this).trigger('sync');
});

Which allows me to have elements like this in my application:这允许我在我的应用程序中拥有这样的元素:

<input type="text" data-url="/controller/action/" class="update">

Which get updated when the user is "done typing" (no action for 2 seconds) or goes to another field (blurs out of the element)当用户“完成输入”(2 秒内无操作)或转到另一个字段(从元素中模糊)时,哪个会更新

If you need wait until user is finished with typing use simple this:如果您需要等到用户完成输入,请使用以下简单操作:

$(document).on('change','#PageSize', function () {
    //Do something after new value in #PageSize       
});

Complete Example with ajax call - this working for my pager - count of item per list:使用 ajax 调用的完整示例 - 这适用于我的寻呼机 - 每个列表的项目计数:

$(document).ready(function () {
    $(document).on('change','#PageSize', function (e) {
        e.preventDefault();
        var page = 1;
        var pagesize = $("#PageSize").val();
        var q = $("#q").val();
        $.ajax({
            url: '@Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
            data: { q: q, pagesize: pagesize, page: page },
            type: 'post',
            datatype: "json",
            success: function (data) {
                $('#tablecontainer').html(data);
               // toastr.success('Pager has been changed', "Success!");
            },
            error: function (jqXHR, exception) {
                ShowErrorMessage(jqXHR, exception);
            }
        });  
    });
});    

Once you detect focus on the text box, on key up do a timeout check, and reset it each time it's triggered.一旦您检测到文本框上的焦点,在按键上进行超时检查,并在每次触发时重置它。

When the timeout completes, do your ajax request.超时完成后,执行您的 ajax 请求。

Simple and easy to understand.简单易懂。

var mySearchTimeout;
$('#ctl00_mainContent_CaseSearch').keyup(function () {
   clearTimeout(mySearchTimeout);
   var filter = $(this).val();
   mySearchTimeout = setTimeout(function () { myAjaxCall(filter); }, 700);
   return true;
});

For passing parameters to your function along with ES6 syntax.用于将参数与 ES6 语法一起传递给您的函数。

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

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

Not a direct answer bu if someone looking for an AngularJS solution.如果有人在寻找 AngularJS 解决方案,则不是直接答案。 I wrote a directive according to the popular solutions here.我根据这里流行的解决方案编写了一个指令。

 app.directive("ngTypeEnds", ["$timeout", function ($timeout) {
    return function (scope, element, attrs) {
        var typingTimer;               
        element.bind("keyup", function (event) {
            if (typingTimer)
                $timeout.cancel(typingTimer);
            if (angular.element(element)[0].value) {
                typingTimer = $timeout(function () {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngTypeEnds);
                    });
                }, 500);
            }
            event.preventDefault();
        });
    };
}]);

You guys have heard of closures in javascript ?!你们听说过javascript中的闭包吗?!

it's very simple and straightforward just compare you current input value with the old value that the setTimeOut function closes over, and voila, you're done.它非常简单直接,只需将您当前的输入值与 setTimeOut 函数关闭的旧值进行比较,瞧,您就完成了。

let timer;
$('#myInput').on('keyup', function() {
  window.clearTimeout(timer);
  // here is the closures javascript magic happens.
  const value = $(this).val();
  timer = setTimeout(() => {
    if(value === $(this).val() && $(this).val()!== ''){
        alert($(this).val());
    }
  }, 500);
})

I needed mine to run for a specific control and this worked for me :我需要我的运行特定控件,这对我有用:

function debounce(func, timeout) {
            let timer;
            return (...args) => {
                clearTimeout(timer);
                timer = setTimeout(() => { func.apply(this, args); }, timeout);
            };
        }

$('#txtFilterClientCode').keyup(debounce(function () {
            console.log("Test");
        }, 1000));

Here is a solution that fires after 1 second of not typing, but also fires instantly when the input is blank.这是一个解决方案,它在 1 秒不输入后触发,但在输入为空白时也会立即触发。 This is useful when clearing search results after the user deletes the input query.这在用户删除输入查询后清除搜索结果时很有用。 This solution also supports copying and pasting into the search box.该解决方案还支持复制粘贴到搜索框中。 The $(() => { ... }); $(() => { ... }); wrapping the top portion of code simply means "do this when the page is loaded" in simple Jquery terms.用简单的 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);
}

for alpine.js users <input @input.debounce.500ms="fn()">对于 alpine.js 用户 <input @input.debounce.500ms="fn()">

Wow, even 3 comments are pretty correct!哇,即使是3条评论也很正确!

  1. Empty input is not a reason to skip function call, eg I remove waste parameter from url before redirect空输入不是跳过函数调用的原因,例如我在重定向之前从 url 中删除了浪费参数

  2. .on ('input', function() { ... }); should be used to trigger keyup , paste and change events应该用于触发keyuppastechange事件

  3. definitely .val() or .value must be used绝对必须使用.val().value

  4. You can use $(this) inside event function instead of #id to work with multiple inputs您可以在事件函数中使用$(this)而不是#id来处理多个输入

  5. (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); (我的决定)我使用匿名函数而不是setTimeout中的doneTyping从 n.4 轻松访问$(this) ,但您需要先保存它,如var $currentInput = $(this);

EDIT I see that some people don't understand directions without the possibility to copy-paste ready code.编辑我看到有些人在没有复制粘贴就绪代码的可能性的情况下不理解方向。 Here you're你来了

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);      
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM