//
// $('#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',function(e){
// This catches the backspace button in chrome, but also prevents
// the event from triggering too premptively. 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()));
});
三种方案:
如果用户输入的内容是是固定长度的文本,比如说手机号码、身份证号码等等,则用keyup()事件监听input中内容length的变化,一旦达到临界值,就表示输入完成,自动提交
监听focus事件,当失去focus时提交(这是我最常用的)
如一楼,做延时处理,你的条件是用户连续输入,当监听到用户在2s之内没有输入时,提交
如果还有更好的方案,请立即通知我!
本身没有这样的事件吧,你可以考虑做个延时处理,比如延时1s,每次有输入重置计时器
通过keyUp事件和时间戳来判断吧
监听Enter事件或focus事件
可以用change事件来监听输入框内容是否发生变化,缺点是只有当输入框失去焦点时才会触发.
html5还有个oninput事件,只要输入框内容发生变化就会立即触发.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/o...
如果是老版本的ie,可以用propertychange | onpropertychange
https://msdn.microsoft.com/library/ms536956(v=vs.85).aspx
触发后可以延时1s,如果有变化清空计时,直到达到延时的时间,然后处理数据即可。
建议还是老老实实用个button吧,因为用户自己都不知道什么时候算输入完毕,例如
以前用过个插件,非常方便。
https://github.com/kenshin54/jquery-koala
Talk is easy, here is the code:
source: http://stackoverflow.com/questions/14042193/how-to-trigger-an-event-in-input-text-after-i-stop-typing-writing
可以用一个debounce方法,做空闲时间的间隔控制,是空闲时间必须大于或等于一定值(wait)的时候,才会执行调用方法。
用法参考
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
不過是 throttling 而已。
https://en.wikipedia.org/wiki/Throttling_process_(computing)
关键词:函数节流