如何自定义格式化Autocomplete插件结果?

dev*_*per 167 javascript jquery jquery-ui jquery-ui-autocomplete

我正在使用jQuery UI Autocomplete插件.有没有办法在下拉结果中突出显示搜索字符序列?

例如,如果我将"foo bar"作为数据并输入"foo",我将在下拉列表中显示" foo bar",如下所示:

Che*_*eso 231

使用实时建议自动完成

是的,如果你修补自动填充,你可以.

在jQuery UI的v1.8rc3中包含的自动完成小部件中,将在自动完成小部件的_renderMenu函数中创建建议弹出窗口.此函数定义如下:

_renderMenu: function( ul, items ) {
    var self = this;
    $.each( items, function( index, item ) {
        self._renderItem( ul, item );
    });
},
Run Code Online (Sandbox Code Playgroud)

_renderItem函数定义如下:

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "</a>" )
        .appendTo( ul );
},
Run Code Online (Sandbox Code Playgroud)

因此,您需要做的是将_renderItem fn替换为您自己的创建,以产生所需的效果.这种技术,重新定义了库中的内部函数,我来学习称为猴子修补.我是这样做的:

  function monkeyPatchAutocomplete() {

      // don't really need this, but in case I did, I could store it and chain
      var oldFn = $.ui.autocomplete.prototype._renderItem;

      $.ui.autocomplete.prototype._renderItem = function( ul, item) {
          var re = new RegExp("^" + this.term) ;
          var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + 
                  this.term + 
                  "</span>");
          return $( "<li></li>" )
              .data( "item.autocomplete", item )
              .append( "<a>" + t + "</a>" )
              .appendTo( ul );
      };
  }
Run Code Online (Sandbox Code Playgroud)

将该功能调用一次$(document).ready(...).

现在,这是一个黑客,因为:

  • 为列表中呈现的每个项目创建了一个正则表达式obj.该正则表达式obj应该被重用于所有项目.

  • 没有用于完成部件格式化的css类.这是一种内联风格.
    这意味着如果您在同一页面上有多个自动填充功能,那么它们都会得到相同的处理.css风格可以解决这个问题.

...但它说明了主要技术,它适用于您的基本要求.

替代文字

更新的工作示例:http://output.jsbin.com/qixaxinuhe


要保留匹配字符串的大小写,而不是使用键入字符的大小写,请使用以下行:

var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + 
          "$&" + 
          "</span>");
Run Code Online (Sandbox Code Playgroud)

换句话说,从上面的原始代码开始,您只需要替换this.term"$&".


编辑
以上内容更改了页面上的每个自动完成小部件.如果您只想更改一个,请参阅此问题:
如何在页面上仅修补一个*自动完成实例?

  • 我要说的一件事是,如果你想让它在匹配字符串的任何部分(不仅仅是开头)加粗结果,请将RegExp行修改为:var re = new RegExp(this.term); (4认同)

Raj*_*Raj 65

这也有效:

       $.ui.autocomplete.prototype._renderItem = function (ul, item) {
            item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
        };
Run Code Online (Sandbox Code Playgroud)

@JörnZaefferer和@ Cheeso的回应组合.

  • 这很好用.唯一需要注意的是item.label正在被替换.对我来说,我在文本框中得到了"<strong ...".只需将替换结果分配给另一个变量即可清除.如果您的数据包含一个放在文本框中的value属性,则不会出现此问题. (3认同)

oro*_*olo 8

超级有帮助.谢谢.+1.

这是一个轻量级版本,对"字符串必须以术语开头"排序:

function hackAutocomplete(){

    $.extend($.ui.autocomplete, {
        filter: function(array, term){
            var matcher = new RegExp("^" + term, "i");

            return $.grep(array, function(value){
                return matcher.test(value.label || value.value || value);
            });
        }
    });
}

hackAutocomplete();
Run Code Online (Sandbox Code Playgroud)


79I*_*9IT 6

jQueryUI 1.9.0改变了_renderItem的工作方式.

下面的代码考虑了这一变化,并展示了我如何使用JörnZaefferer的jQuery Autocomplete插件进行高亮匹配.它将突出显示整个搜索字词中的所有单个字词.

由于转向使用Knockout和jqAuto,我发现这是一种更简单的样式化结果.

function monkeyPatchAutocomplete() {
   $.ui.autocomplete.prototype._renderItem = function (ul, item) {

      // Escape any regex syntax inside this.term
      var cleanTerm = this.term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

      // Build pipe separated string of terms to highlight
      var keywords = $.trim(cleanTerm).replace('  ', ' ').split(' ').join('|');

      // Get the new label text to use with matched terms wrapped
      // in a span tag with a class to do the highlighting
      var re = new RegExp("(" + keywords + ")", "gi");
      var output = item.label.replace(re,  
         '<span class="ui-menu-item-highlight">$1</span>');

      return $("<li>")
         .append($("<a>").html(output))
         .appendTo(ul);
   };
};

$(function () {
   monkeyPatchAutocomplete();
});
Run Code Online (Sandbox Code Playgroud)


Fab*_*sco 6

在这里,一个功能完整的例子:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Autocomplete - jQuery</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <label for="search"></label>
  <input type="text" name="search" id="search" />
</form>

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
$(function(){

$.ui.autocomplete.prototype._renderItem = function (ul, item) {
    item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
    return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.label + "</a>")
            .appendTo(ul);
};


var availableTags = [
    "JavaScript",
    "ActionScript",
    "C++",
    "Delphi",
    "Cobol",
    "Java",
    "Ruby",
    "Python",
    "Perl",
    "Groove",
    "Lisp",
    "Pascal",
    "Assembly",
    "Cliper",
];

$('#search').autocomplete({
    source: availableTags,
    minLength: 3
});


});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助