用户完成键入后,调整keyup事件以调用API



我有一个邮政编码字段,该字段有一个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">

相关内容

  • 没有找到相关文章

最新更新