【问题标题】:Jquery live search, doesnt exit if statement once content is removed from the inputJquery实时搜索,一旦从输入中删除内容,就不会退出if语句
【发布时间】:2023-03-29 09:50:01
【问题描述】:

我目前正在完成作为网络开发人员培训的最终团队项目。我确实为我们的应用程序编写了一个实时搜索代码,它按预期工作,直到我从输入中删除内容为止。代码有时会保留在 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;

            });

        }
    }


 });


});

感谢您的帮助。

祝你有美好的一天。

【问题讨论】:

  • 您能出示您的完整代码吗?如果可能的话,创建一个小提琴。

标签: jquery livesearch


【解决方案1】:

您似乎使用计数变量使事情变得过于复杂。现在,您的 ajax 调用仅每 3 次按键触发(这意味着例如按 3 次 shift 将触发它或按住一个字母只会将计数增加 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);
    }
  });
});

【讨论】:

  • 谢谢,感谢您的帮助!是的,有了计时器,这已经很顺畅了。但是现在如果输入为空,它不再删除内容。
  • 我该怎么做?在此处或我的个人资料中都看不到任何选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多