自动完成功能无法正常工作

时间:2020-06-22 16:46:37

标签: javascript jquery jquery-ui autocomplete jquery-ui-autocomplete

<html>
<head>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<title>Welcome to the page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script> 
</head>
<body>
<input type="text" id="suggestion" />
</body>

<script type="text/javascript">
$.getJSON( "data.json", function( data ) {
      
      var data_arr = data.map(function(val){
                 return val.name;
        })
       
       auto(data_arr)
     });
         
    function auto(data_arr){

        $('#suggestion').autocomplete({
            source: data_arr    
        }).data("ui-autocomplete")._renderMenu = function (ul, items) {
            var that = this;
            var val = that.element.val();
            $.each($.grep(items, function (value, key) {
                return new RegExp(val.toLowerCase()).test(value.value.toLowerCase().slice(0, val.length))
            }), function (index, item) {
                that._renderItemData(ul, item);
            });
        };
    }
    
</script>
</html>

Data.json

[  
        {
            "id": "136599",
            "name": "CE712A#BGJ"
        },
        {
            "id": "137704",
            "name": "12C#ABA"
        },
        {
            "id": "137705",
            "name": "F2212A#ABA"
        }
]

以上代码适用于data.json文件中存在的所需值。一旦输入了data.json文件以外的任何其他值,该建议就会弹出并消失。当data.json中不存在输入时,我实际上不希望什么也不显示。请帮我。

1 个答案:

答案 0 :(得分:0)

请考虑以下内容:

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<input type="text" id="suggestion" />
<script type="text/javascript">
  $('#suggestion').autocomplete({
    source: function(req, resp) {
      $.getJSON("data.json", function(data) {
        var data_arr = $.ui.autocomplete.filter(data.map(function(val) {
          return val.name;
        }), req.term);
        resp(data_arr);
      });
    }
  });
</script>

如果对源使用功能,则可以在将JSON输出的结果传递给自动完成功能之前对其进行调整。如果需要,您可以考虑将它们映射到labelvalue对。

查看更多:https://api.jqueryui.com/autocomplete/