自动完成 jquery 功能

autocomplete jquery function

我想做的是使用 jquery 自动完成并在匹配 titlekeywords 时显示标题 This是我拥有的代码,但我无法让它按照我需要的方式工作,如果我将它放入常规数组而不是标题和关键字,我已经能够让它搜索标题。任何帮助都会非常好,提前致谢。

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);
    }
});

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

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">