【问题标题】:how to make bold matched text in autocomplete jquery如何在自动完成jQuery中制作粗体匹配文本
【发布时间】:2021-09-06 00:51:12
【问题描述】:

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

这是我的代码:

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

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

【问题讨论】:

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


【解决方案1】:

考虑以下示例。

$(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>

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

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

【讨论】:

  • 非常感谢您,先生,我最近几天一直在寻找,您太棒了。上帝祝福你。干杯!
猜你喜欢
  • 2011-03-21
  • 1970-01-01
  • 2016-07-26
  • 2019-08-26
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2018-08-10
相关资源
最近更新 更多