如何过滤我的搜索输入jQuery自动完成功能?

时间:2019-02-07 15:34:25

标签: javascript jquery

我遇到一个问题,当用户搜索一个值时,它会显示所有值,而不是过滤我的值。当我搜索html时,我希望它仅显示html作为我的值,而不是我的所有值。请帮忙。谢谢。

这是我的代码:

$(function() {
  function log(message) {
    $("<div>").text(message).prependTo("#log");
    $("#log").scrollTop(0);
  }
  $("#html").autocomplete({
    source: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/html-elements.json",
    minLength: 1,
    select: function(event, ui) {

      log(ui.item ?
        "Selected: " + ui.item.value + " element " :
        "Nothing selected, input was " + this.value);

    }

  });
});
.ui-autocomplete-loading {
  background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.js" ></script>

<div class="ui-widget">
  <label for="html">HTML Elements: </label>
  <input id="html">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

2 个答案:

答案 0 :(得分:0)

似乎源URL没有响应过滤器。您可以先进行调用,然后将所有结果保存到变量中,然后设置自动完成

let dataVariable;
$.ajax({
  method: "POST",
  url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/html-elements.json",",
  success:function(data){
   dataVariable=data;
 }
})
  .done(function( msg ) {
    $("#html").autocomplete({
    source: data,
    minLength: 1,
    select: function(event, ui) {

      log(ui.item ?
        "Selected: " + ui.item.value + " element " :
        "Nothing selected, input was " + this.value);
     }
   });
  });

答案 1 :(得分:0)

$(function() {
  function log(message) {
    $("<div>").text(message).prependTo("#log");
    $("#log").scrollTop(0);
  }


  $.get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/html-elements.json", function(data) {
    $("#html").autocomplete({
      source: data,
      minLength: 1,
      select: function(event, ui) {
        log(ui.item ?
          "Selected: " + ui.item.value + " element " :
          "Nothing selected, input was " + this.value);
      }
    });
  })
});
.ui-autocomplete-loading {
  background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="ui-widget">
  <label for="html">HTML Elements: </label>
  <input id="html">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>