Highlight jQuery UI autocomplete

后端 未结 3 1382
醉梦人生
醉梦人生 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 $( "
  • " ) .data( "item.autocomplete", item ) .append( $( "" ).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 $( "
  • " ) .data( "item.autocomplete", item ) .append( '' + item.label + '' ) .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 $( "
  • " ) .data( "ui-autocomplete-item", item ) .append( '' + item.label + '' ) .appendTo( ul ); }; });

提交回复
热议问题