停止input/写入后如何在input文本中触发事件?

我想在我input文本框中停止键入(而不是在键入)字符后立即触发一个事件。

我试过:

$('input#username').keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $.post('/ajax/fetch', { type: 'username', value: _this.val() }, function(data) { if(!data.success) { // continue working } else { // throw an error } }, 'json'); }, 3000); }); 

但是这个例子为每个input的字符都产生一个超时,如果input20个字符,我会得到大约20个AJAX请求。

在这个小提琴,我演示了一个简单的警报,而不是一个AJAX相同的问题。

有没有这样的解决scheme,或者我只是用一个坏的方法呢?

你将不得不使用setTimeout (像你一样),但也存储的引用,所以你可以保持重置限制。 就像是:

 // // $('#element').donetyping(callback[, timeout=1000]) // Fires callback when a user has finished typing. This is determined by the time elapsed // since the last keystroke and timeout parameter or the blur event--whichever comes first. // @callback: function to be called when even triggers // @timeout: (default=1000) timeout, in ms, to to wait before triggering event if not // caused by blur. // Requires jQuery 1.7+ // ;(function($){ $.fn.extend({ donetyping: function(callback,timeout){ timeout = timeout || 1e3; // 1 second default timeout var timeoutReference, doneTyping = function(el){ if (!timeoutReference) return; timeoutReference = null; callback.call(el); }; return this.each(function(i,el){ var $el = $(el); // Chrome Fix (Use keyup over keypress to detect backspace) // thank you @palerdot $el.is(':input') && $el.on('keyup keypress paste',function(e){ // This catches the backspace button in chrome, but also prevents // the event from triggering too preemptively. Without this line, // using tab/shift+tab will make the focused element fire the callback. if (e.type=='keyup' && e.keyCode!=8) return; // Check if timeout has been set. If it has, "reset" the clock and // start over again. if (timeoutReference) clearTimeout(timeoutReference); timeoutReference = setTimeout(function(){ // if we made it here, our timeout has elapsed. Fire the // callback doneTyping(el); }, timeout); }).on('blur',function(){ // If we can, fire the event since we're leaving the field doneTyping(el); }); }); } }); })(jQuery); $('#example').donetyping(function(){ $('#example-output').text('Event last fired @ ' + (new Date().toUTCString())); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" id="example" /> <p id="example-output">Nothing yet</p> 

解:

这是解决scheme。 在用户停止键入指定的时间后执行一个function:

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

用法

 $('input').keyup(function() { delay(function(){ alert('Hi, func called'); }, 1000 ); }); 

你可以使用underscore.js“debounce”

 $('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) ); 

这意味着你的函数调用将在按下一个键500ms后执行。 但是如果在500ms之前按下另一个按键(另一个按键事件被触发),则前面的function执行将被忽略(去抖动),并且在新的500ms定时器之后执行新的function。

对于额外的信息,使用_.debounce(func,timer, true )将意味着第一个函数将被执行,随后的500ms定时器的所有其他按键事件将被忽略。

你需要去抖动!

这是一个jQuery插件 ,这里是所有你需要知道的有关debounce 。 如果你从Google来到这里,Underscore已经find了你的应用程序的JSoup的方法,它已经反击了!

清理解决scheme

 $.fn.donetyping = function(callback, delay){ delay || (delay = 1000); var timeoutReference; var doneTyping = function(elt){ if (!timeoutReference) return; timeoutReference = null; callback(elt); }; this.each(function(){ var self = $(this); self.on('keyup',function(){ if(timeoutReference) clearTimeout(timeoutReference); timeoutReference = setTimeout(function(){ doneTyping(self); }, delay); }).on('blur',function(){ doneTyping(self); }); }); return this; }; 

有一个简单的插件,我做了,做到了这一点。 它比所提出的解决scheme需要的代码less得多,而且非常轻(〜0,6kb)

首先,您可以创build比任何时候都可以bumped Bid对象。 每次碰撞都会延迟发射下一次给定的时间。

 var searchBid = new Bid(function(inputValue){ //your action when user will stop writing for 200ms. yourSpecialAction(inputValue); }, 200); //we set delay time of every bump to 200ms 

Bid对象准备就绪时,我们需要以某种方式对其进行调整。 让我们来附加碰撞keyup event

 $("input").keyup(function(){ searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback }); 

这里发生的是:

每次用户按键,下一个200ms的投标就被“延迟”(碰撞)。 如果200ms通过而不再发生“碰撞”,callback将被解雇。

此外,您还有2个额外的function用于停止出价(例如,如果用户按下esc或单击外部input),并立即完成并触发回叫(例如,当用户按回车键时):

 searchBid.stop(); searchBid.finish(valueToPass); 

我一直在寻找一个简单的HTML / JS代码,我没有find任何。 然后,我使用onkeyup="DelayedSubmission()"编写了下面的代码。

 <!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> 

在我看来,当用户不关注该input时,用户会停止写作。 为此,你有一个叫做“模糊”的function, 就像这样