一旦看起来用户已完成输入,就调整keyup事件以调用API

时间:2016-01-11 10:08:51

标签: javascript jquery input user-input client-side

我有一个包含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);
    }
});

3 个答案:

答案 0 :(得分:8)

您可以使用setTimeout仅在键入已停止250ms后进行呼叫 - 这通常是在击键之间足以允许完整输入的时间。试试这个:

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);
});

如果您觉得有太多延迟,您可以调整确切的超时以更好地满足您的需求。

答案 1 :(得分:1)

这是一个功能装饰器,它会将事件延迟到最后一次按键。你可以玩延迟时间来获得最佳感觉。 200ms是任意值。

&#13;
&#13;
$("#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);
  }
}
&#13;
<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">
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果您还没有尝试过,也可以尝试在代码中使用.blur()而不是.keyup()。