jQuery UI 自动完成突出显示完整单词而不是匹配的子字符串

jQuery UI autocomplete highlight full word instead of matched substring

我正在创建自动完成功能。一切正常。但我需要突出显示包含匹配文本的整个单词。例如:

src = ['Apple', 'America', 'Apes', 'Battle of the Apes']

如果用户输入 "Ap" 我得到

Apple
Apes
Apes

之战

我想要的:

苹果
猿类
猩猩之战

$(document).ready(function(){
    $("#searchresult").autocomplete({
        source       :'autocomplete.php',
        minLength    : 1,
        selectFirst  : true,
        matchContains: true,
        scroll       : false,
        appendTo     : '#menucontainer',
        autoFocus    : true,
        select       : function( event, ui ) { 
            window.location.href = ui.item.value;
            ui.item.value=ui.item.label;
        }
    })
    .data( "autocomplete" )._renderItem = function( ul, item ) {
        var term = this.element.val(),
            regex = new RegExp( '(' + term + ')', 'gi' );
        t = item.label.replace( regex , "<b>$&</b>" );
        return $( "<li></li>" ).data("item.autocomplete", item)
            .append( "<a style='height:30px;'><div style='width: 100%; float: left;overflow: hidden; white-space:nowrap; text-overflow: ellipsis; text-align: left;'>" + t + "</div><div style='right: 0; position: relative; float:right; font-size: 11px;margin-top:-15px; color: #b3b3b3;'>" + item.cate + "</div></a>")
            .appendTo( ul );
    }
});

您的正则表达式有误。您正在匹配术语而不是匹配整个单词。试试这个:

regex = new RegExp('\S*' + term + '\S*', 'gi');

此正则表达式将匹配单词周围非空格的所有内容。