0

为什么在触发之前需要超过 5 次击键?

$( document ).ready(function() {

  $("#zipcode").on("keyup", function(event) { // keyup function

    if(this.value.length == 5){ // if 5 time keyup then fire the ajax 

        var zicpcode= $("#zipcode").val(); // get the value of zipcode

        $.ajax({
            url: "http://pages.em.essilorusa.com/page.aspx?QS=773ed3059447707d2a7242227e94bba8efcc7ce6da09facd&zip="+zicpcode,
            type: "get", //send it through get method
             success: function(results) {
                var res = results.substring((results.indexOf("<rs1>")+5),results.indexOf("</rs1>"));
                var splitted = res.split("|");
                var distinct = [];
                $.each(splitted , function(i, el){
                    if($.inArray(el, distinct ) === -1) 
                        distinct.push(el);
                });
                $("#zipcode").autocomplete({ source: distinct }); 
              },
        });
    }

  });

});

它工作正常,但有一个额外的击键或退格键。

4

1 回答 1

0
$(document).ready(function() {
    splitted = []; // Inialization empty array 
    $("#zipcode").autocomplete({
        source: splitted
    }); //Inialization for enabling the feature of Auto-complete
    $("#zipcode").keyup(function(event) {
        if (this.value.length == 5) {


            var zicpcode = $("#zipcode").val();
            $.ajax({
                url: "http://pages.em.essilorusa.com/page.aspx?QS=773ed3059447707d2a7242227e94bba8efcc7ce6da09facd&zip=" + zicpcode,
                type: "get", //send it through get method
                async: false,
                success: function(results) {
                    var res = results.substring((results.indexOf("<rs1>") + 5), results.indexOf("</rs1>"));
                    var splitted = res.split("|");
                    $("#zipcode").autocomplete({
                        source: splitted
                    });
                },
            });

        }
    });
});
于 2015-10-29T22:39:12.737 回答