自动完成jQuery功能

时间:2018-07-18 18:45:01

标签: javascript jquery jquery-ui-autocomplete

我想做的是使用jquery自动完成功能,并在匹配 title keywords 的情况下显示标题。这是我的代码,但我无法获取按照我需要的方式工作,如果我将其放在常规数组中而不是标题和关键字,就可以使它搜索标题。任何帮助都将是非常好的,在此先感谢您。

var VideoNames = [{title: "superman", keywords: "super man hero movie"}]

$("#searchbox").autocomplete({
    source: VideoNames,
    select: function (event, ui) {
        $("#searchbox").val(ui.item.value);
        TrainingVideos.search(ui.item.value);
    }
});

1 个答案:

答案 0 :(得分:1)

要获得这种结果,您应该使用source的设置对象的autocomplete属性的函数变体。每次输入值更改时都会调用该函数。因此,您需要返回匹配的标题数组。为此,使用请求项作为模式创建一个新的RegExp对象。然后使用RegExp对象匹配原始数组的项目的标题和关键字。最后,将它们映射为仅显示标题。结果如下:

const videos = [
  {
    title: "superman",
    keywords: "super man hero movie"
  },
  {
    title: "batman",
    keywords: "batmobile driving guy"
  },
  {
    title: "captain america",
    keywords: "hero star us"
  }
]

$("#searchbox").autocomplete({
  source (request, response) {
    const matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i")
    
    response(
      videos
        .filter(item => matcher.test(item.title + item.keywords))
        .map(item => item.title)
    )
  }
});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<input id="searchbox">