Jquery实时搜索,一旦从输入中删除内容,就不会退出if语句

时间:2018-04-20 06:30:01

标签: jquery livesearch

我目前正在作为网络开发人员进行培训的最终团队项目。我确实为我们的应用程序编写了一个实时搜索代码,它按预期工作,直到我从输入中删除内容为止。代码有时会保留在if语句中以删除追加。我不明白为什么。有人知道吗?

这是我的代码:

$(function(){

 var check = 0;

 $("#getQuestions").on("keyup", function(){
    check++;

    var inputLength = $("#getQuestions").val().length;

    if (check === 3 || inputLength === 0) {

        $(".liveSearch").remove();

    }
    if (inputLength >= 1) {

        if(check === 3 ){

            $.ajax({

                type: "POST",
                url: "/getQuestions",
                data: {"question": $("#getQuestions").val()}

            }).done(function(response){

                for (var i = 0; i < response.length; i++) {

                    var id = response[i].id;
                    var title = response[i].title;
                    $("#listQuestions").append('<div class="liveSearch"><a href="/question?id='+id +'""' + '>' + title + '</a></div>' );

                }

                check = 0;

            });

        }
    }


 });


});

我很感激帮助。

度过愉快的一天。

1 个答案:

答案 0 :(得分:0)

使用count var似乎过于复杂化了。现在你的ajax调用仅触发每3个键上升(这意味着例如按3次按键将触发它或按下并按住一个字母只会使计数增加1)。

通过使用按键和计时器,您将获得以下代码:

$(function(){
  var timer;
  $("#getQuestions").on("keypress", function(){
    if ($("#getQuestions").val().length == 0) {
      $(".liveSearch").remove();
    }
    if ($("#getQuestions").val().length > 0) {
      clearTimeout(timer);
      timer = setTimeout(function() {
        $(".liveSearch").remove();
        $.ajax({
          type: "POST",
          url: "/getQuestions",
          data: {"question": $("#getQuestions").val()}
        }).done(function(response){
          for (var i = 0; i < response.length; i++) {
            $("#listQuestions").append('<div class="liveSearch"><a href="/question?id=' + response[i].id + '">' + response[i].title + '</a></div>');
          }
        });
      }, 1000);
    }
  });
});