用户完成键入后,调整keyup事件以调用API
Tweaking on keyup event to call API once it appears user has finished typing
我有一个邮政编码字段,该字段有一个jQuery-onKeyup事件-想法是,一旦他们完全输入了他们的邮政编码,就调用Google Maps Geocoding API,立即根据该邮政编码获取位置。
这段代码有效,但我想找到一个解决方案,理想情况下不会多次调用API,而是等待用户是否使用某种方法完成了键入,即等待x时间,然后调用API。
有人能提出最好的方法吗?
$("#txtPostcode").keyup(function() {
var postcode = $('#txtPostcode').val().length
if (postcode.length >= 5 && postcode.length <= 8) {
console.log('length is a valid UK length for a postcode');
// some logic here to run with some way to work out if user has 'finished' typing
callGoogleGeocodingAPI(postcode);
}
});
您可以使用setTimeout
仅在键入停止250毫秒后进行调用-这通常是两次击键之间的足够时间,以允许完整输入。试试这个:
var timer;
$("#txtPostcode").keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
var postcode = $('#txtPostcode').val().length
if (postcode.length >= 5 && postcode.length <= 8) {
console.log('length is a valid UK length for a postcode');
// some logic here to run with some way to work out if user has 'finished' typing
callGoogleGeocodingAPI(postcode);
}
}, 250);
});
如果你觉得延迟太多,你可以调整确切的超时时间,以更好地满足你的需求。
如果您还没有尝试过,也可以尝试在代码中使用.blur()而不是.keyup()。
这里有一个函数装饰器,它将事件延迟到最后一次按键。你可以利用延迟时间来获得最佳感觉。200ms是一个任意值。
$("#txtPostcode").keyup(delayEvent( function( e ) {
console.log( 'event fired' );
// this refers to the element clicked, and there is an issue with in the if statement
// you are checking postcode.length.length which probably throws an error.
var postcode = $(this).val();
if (postcode.length >= 5 && postcode.length <= 8) {
console.log('length is a valid UK length for a postcode');
// some logic here to run with some way to work out if user has 'finished' typing
// callGoogleGeocodingAPI(postcode);
}
}, 200));
// this is a functional decorator, that curries the delay and callback function
// returning the actual event function that is run by the keyup handler
function delayEvent( fn, delay ) {
var timer = null;
// this is the actual function that gets run.
return function(e) {
var self = this;
// if the timeout exists clear it
timer && clearTimeout(timer);
// set a new timout
timer = setTimeout(function() {
return fn.call(self, e);
}, delay || 200);
}
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtPostcode">
相关文章:
- keyup事件处理程序更改焦点不适用于快速键入
- 访问代码生成的输入元素上的keyup事件
- jQuery调用keyup事件不起作用
- jQuery keyup事件增加-“;函数“;将设置为0
- Backbone.js ModelBinder将默认事件更改为keyup
- Keyup事件在easyui上不起作用
- 将变量传递到keyup事件内部
- JS在input标签上使用keyup事件进行搜索
- Keyup 事件侦听器在 Chrome 的 Ominbox 上按下 Enter 时触发
- 如何将 fn 去抖动实现到 jQuery keyup 事件中
- 如何在 keyup 事件上匹配数组中的字符串
- 为什么在Mac浏览器上按下metaKey时,Javascript会丢弃keyUp事件
- jQuery,keyup事件未启动
- 在keyup事件中指定click事件处理程序会导致click事件被多次激发
- 使用AngularJS对超快速keyup和keydown事件调用函数
- 如何在发送keyup事件时避免出现比赛情况
- 通过jQueryAJAX和keyup事件搜索特定的术语
- 在文本区域中的Keyup事件上触发Twitter Bootstrap Popover
- 如何从jQuery插件中附加keyup事件
- jQuery Keyup 事件仅在页面加载时调用