我想触发一个事件就在我停止打字(不打字时)字符在我的输入文本框。
我试着:
$('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);
});
但这个例子中产生对每个键入的字符超时,我得到约20 AJAX请求,如果我类型的20个字符。
在这拨弄我演示了一个简单的警告,而不是一个AJAX同样的问题。
是否有一个解决方案或我只是用这个不好的做法?
Answer 1:
你将不得不使用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>
将执行时:
- 超时已过,或
- 用户切换字段(
blur
事件)
(以先到者为准)
Answer 2:
解:
这里是解决方案。 执行功能的用户已经停止打字指定的时间量后:
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 );
});
Answer 3:
您可以使用underscore.js“反跳”
$('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) );
这意味着你的函数调用将按下一个键后500毫秒执行。 但是,如果你按另一个键(按键的另一触发事件)在500毫秒之前,前一个函数的执行将被忽略(去抖动)和一个新的500ms的计时器之后的新一个将被执行。
对于额外的信息,使用_.debounce(FUNC,定时器,true)就意味着第一个函数将执行和后续withing 500ms的定时器所有其他按键事件将被忽略。
Answer 4:
你需要抖!
这里是一个jQuery插件 ,这里是所有你需要知道的关于反跳 。 如果您是从谷歌和下划线来这里已经找到了它的方式进入您的应用程序的JSoup,它有反跳右出炉 !
Answer 5:
清洁液:
$.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;
};
Answer 6:
有一些简单的插件,我做了,做exacly这一点。 它需要更少的代码比提出的解决方案,这是非常轻(〜0,6kb)
首先,创建Bid
对象相比,可以bumped
任何时候。 每次撞击将推迟发射投标回调的下一个时间给出ammount的。
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
对象是准备好了,我们需要bump
不知它。 让我们重视对撞keyup
event
。
$("input").keyup(function(){
searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback
});
这里发生的是:
每次用户按下按键,出价“延时”(碰撞)为下200毫秒。 如果200毫秒将通过不beeing“撞”了,回调将被解雇。
此外,你有2个额外的功能停止投标(如果用户按下Esc键或点击之外,例如输入)和整理,并立即解雇回调(例如,当用户按回车键):
searchBid.stop();
searchBid.finish(valueToPass);
Answer 7:
我一直在寻找一个简单的HTML / JS代码,我没有发现任何。 然后,我写下面使用的代码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>
Answer 8:
你应该分配setTimeout
给一个变量,并使用clearTimeout
来清除它的按键。
var timer = '';
$('input#username').keypress(function() {
clearTimeout(timer);
timer = setTimeout(function() {
//Your code here
//Your code here
}, 3000); //Waits for 3 seconds after last keypress to execute the above lines of code
});
小提琴
希望这可以帮助。
Answer 9:
为什么那么多当你只是想重新设置时钟?
var clockResetIndex = 0 ;
// this is the input we are tracking
var tarGetInput = $('input#username');
tarGetInput.on( 'keyup keypress paste' , ()=>{
// reset any privious clock:
if (clockResetIndex !== 0) clearTimeout(clockResetIndex);
// set a new clock ( timeout )
clockResetIndex = setTimeout(() => {
// your code goes here :
console.log( new Date() , tarGetInput.val())
}, 1000);
});
如果你是在WordPress的工作,那么你需要用一个jQuery的块内的所有代码:
jQuery(document).ready(($) => {
/**
* @name 'navSearch'
* @version 1.0
* Created on: 2018-08-28 17:59:31
* GMT+0530 (India Standard Time)
* @author : ...
* @description ....
*/
var clockResetIndex = 0 ;
// this is the input we are tracking
var tarGetInput = $('input#username');
tarGetInput.on( 'keyup keypress paste' , ()=>{
// reset any privious clock:
if (clockResetIndex !== 0) clearTimeout(clockResetIndex);
// set a new clock ( timeout )
clockResetIndex = setTimeout(() => {
// your code goes here :
console.log( new Date() , tarGetInput.val())
}, 1000);
});
});
Answer 10:
在我的思想用户停止写作时他不守关注那些输入。 对于这一点,你有一个叫做“模糊”功能这东西不一样
文章来源: How to trigger an event in input text after I stop typing/writing?