5

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

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

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

因此,我正在尝试使用自动完成功能的突出显示选项来解决此问题,您可以在其中使用函数对结果执行一些自定义操作。目前我有这个:

$('.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

有任何想法吗?

4

3 回答 3

11

使用RegExp构造函数从字符串创建RegExp对象:

$('.autocomplete').autocomplete('getmatch.php', {
    highlight: function(match, keywords) {
        keywords = keywords.split(' ').join('|');
        return match.replace(new RegExp("("+keywords+")", "gi"),'<b>$1</b>');
    }
});
于 2009-06-05T17:56:19.973 回答
1

我调整了最初的自动完成实现,因为上面的内容被简化了,并且不会处理术语中的 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>");
}
于 2009-09-28T14:19:42.743 回答
0

你的函数应该使用这个签名:function(value, term)。值和术语将由自动完成插件填充并具有您需要的值。

于 2009-06-05T18:04:59.850 回答