代码之家  ›  专栏  ›  技术社区  ›  Alec

突出显示jQuery.autocomplete的多个关键字

  •  5
  • Alec  · 技术社区  · 16 年前

    我正在使用jQuery Autocomplete plugin ,但我对结果突出显示有一些问题。如果找到匹配项,但输入的关键字包含空格,则不会突出显示。例子:

    搜索=“foo”,结果=“foo-bar”,显示=” 酒吧“

    搜索=“foo-ba”,结果=“foo-bar”,显示=“foo-bar”

    highlight option 在自动完成函数中,您可以使用函数对结果执行一些自定义操作。目前我有:

    $('.autocomplete').autocomplete('getmatch.php', {
        highlight: function(match, keywords) {
            keywords = keywords.split(' ').join('|');
            return match.replace(/(get|keywords|here)/gi,'<b>$1</b>');
        }
    });

    replace函数用一个粗体版本替换字符串中所有匹配的单词,该版本有效。但是,我不知道如何将关键字放入该函数中。我想我会把它们分开,然后用一个“|”把它们连在一起,所以“foo-bar”就变成了“foo-bar”。但像这样的事情似乎不起作用:

    return match.replace(/(keywords)/gi,'<b>$1</b>'); // seen as text, I think

    return match.replace('/'+(keywords)+'/gi','<b>$1</b>'); // nothing either

    有什么想法吗?

    3 回复  |  直到 16 年前
        1
  •  11
  •   Gumbo    16 年前

    使用 RegExp constructor 正则表达式

    $('.autocomplete').autocomplete('getmatch.php', {
        highlight: function(match, keywords) {
            keywords = keywords.split(' ').join('|');
            return match.replace(new RegExp("("+keywords+")", "gi"),'<b>$1</b>');
        }
    });
    
        2
  •  1
  •   Shaun    16 年前

    我调整了最初的自动完成实现,因为上面的实现已经简化,并且在术语中不会处理regEx特殊字符。

    function doTheHighlight(value, term) {
        // Escape any regexy type characters so they don't bugger up the other reg ex
        term = term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");
    
        // Join the terms with a pipe as an 'OR'
        term = term.split(' ').join('|');
    
        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
    }
    
        3
  •  0
  •   Zachary    16 年前

    您的函数应该使用以下签名:函数(值、术语)。价值与价值;术语将由自动完成插件填充,并具有所需的值。