如何在自动完成中制作粗体匹配文本 jquery

how to make bold matched text in autocomplete jquery

我需要你的帮助,我正在使用自动完成-Jquery。我需要在自动完成建议的下拉列表中加粗文本。我该怎么办?请在这方面帮助我。谢谢。

这是我的代码:

   $(function () {
        $("#age").autocomplete({
            source: '{% url 'autocomplete' %}',
            appendTo: "#appendToHere",
            select: function(event, ui) {
                selectedItem = ui.item.value;
                document.getElementById("age").value = selectedItem;

                $("#searchBtn").click();
            },
        });
    });

考虑以下示例。

$(function() {
  var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ];

  function boldStr(needle, haystack) {
    var regex = new RegExp(needle, 'i');
    return haystack.replace(regex, "<span class='bold'>" + needle + "</span>");
  }

  $("#tags").autocomplete({
    source: availableTags
  }).autocomplete("instance")._renderItem = function(ul, item) {
    return $("<li>")
      .append("<div>" + boldStr($("#tags").val(), item.label) + "</div>")
      .appendTo(ul);
  };;
});
.bold {
  font-weight: bold;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

您可以使用替换来替换字符串的一部分。查看更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

您可以使用扩展点来修改列表中的项目。查看更多:https://api.jqueryui.com/autocomplete/#method-_renderItem