Highlight jQuery UI autocomplete

后端 未结 3 1383
醉梦人生
醉梦人生 2020-12-29 07:53

I\'m using the autocomplete function in jQuery UI 1.8.6. And I want to highlight matching results. But for some reason when I use a regex to add \"strong\" tags around the m

相关标签:
3条回答
  • 2020-12-29 08:32

    The jQuery autocomplete source code is the culprit. If you look in the actual javascript files, you'll find this definition for displaying items in the autocomplete list:

    _renderItem: function( ul, item) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( $( "<a></a>" ).text( item.label ) )
            .appendTo( ul );
    }
    

    You'll see it's appending ".text(item.label)" which causes the html to be escaped. To solve this, you kind of have to put in a hack to override this "_renderItem" method, replacing the line that appends the label as plain text with a line that appends the label as html. So update your code like this:

    $(function () {
        $("#autocompleteinputfield").autocomplete({
            // leave your code inside here exactly like it was
        })
        .data('autocomplete')._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( '<a>' + item.label + '</a>' )
                .appendTo( ul );
        };
    });
    

    Update: With version >=1.10 of jQuery, there are some small modifications:

    $(function () {
        $("#autocompleteinputfield").autocomplete({
            // leave your code inside here exactly like it was
        })
        .data('ui-autocomplete')._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "ui-autocomplete-item", item )
                .append( '<a>' + item.label + '</a>' )
                .appendTo( ul );
        };
    });
    
    0 讨论(0)
  • 2020-12-29 08:35
    $.extend($.ui.autocomplete.prototype, {
        _renderItem: function (ul, item) {
            var searchMask = this.element.val();
            var regEx = new RegExp(searchMask, "ig");
            var replaceMask = "<b style=\"color:green;\">$&</b>";
            var html = item.label.replace(regEx, replaceMask);
    
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append($("<a></a>").html(html))
                .appendTo(ul);
        }
    });
    
    0 讨论(0)
  • 2020-12-29 08:47

    Plain javascript alert() does not display html. Look into using a modal or something else. Or like the others said, post some specific input/output.

    0 讨论(0)
提交回复
热议问题