Javascript 如何突出显示与已输入文本匹配的 jQuery 自动完成结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7146588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:03:01  来源:igfitidea点击:

How to highlight jQuery Autocomplete results that match the text already typed?

javascriptjqueryjquery-uijquery-autocompletejquery-ui-autocomplete

提问by DaveDev

I've implemented jQuery Autocomplete for a client. Now they want me to highlight (e.g. make bold) the the portion of the result that matches the text they've typed.

我已经为客户实现了 jQuery 自动完成。现在他们要我突出显示(例如加粗)结果中与他们输入的文本相匹配的部分。

e.g. the user types "something", and the results are as follows:

例如用户输入“某物”,结果如下:

somethinga

东西

somethingb

东西b

Another something

另一个东西

Do somethingelse

别的

Is this functionality built into jQuery Autocomplete? If so, what is it?

此功能是否内置于 jQuery 自动完成功能中?如果是,那是什么?

Or is this something I'll have to implement myself? If so, where do I start with that?

或者这是我必须自己实现的东西?如果是这样,我从哪里开始呢?

回答by Zeeshan Eqbal

I had the same requirement previously.

我以前也有同样的要求。

Below code may work for you.

下面的代码可能对你有用。

"You need to be careful with selectors"

“你需要小心选择器”

<script>
  $("#input-search-box")
    .autocomplete({
      //your code
    })
    .data("autocomplete")._renderItem = function(ul, item) {
    var items = $("<li></li>").data("ui-autocomplete-item", item);
    //match and key variables highlight the user's typed input rendering in bold blue for dropdown items.
    var match = new RegExp("^" + this.term, "i"); //i makes the regex case insensitive

    //change initial typed characters of all item.label   replace is plain JS
    var key = item.label.replace(
      match,
      '<span class="required-drop">' + this.term + '</span>'
    );

    items.html("<a>" + key + "</a>").append(ul);
  }; 
</script>

Let me know if you need more help to implement this code.

如果您需要更多帮助来实现此代码,请告诉我。