【问题标题】:jQuery UI autocomplete highlight full word instead of matched substringjQuery UI 自动完成突出显示完整的单词而不是匹配的子字符串
【发布时间】:2015-04-14 11:37:15
【问题描述】:

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

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

如果用户输入“Ap”,我会得到 ​​p>

Apple
Apes
Apses

之战

我想要什么:

苹果

猿人之战

$(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 );
    }
});

【问题讨论】:

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


    【解决方案1】:

    您的正则表达式有错误。您正在匹配该术语以匹配整个单词。试试这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      相关资源
      最近更新 更多