【问题标题】:live highlight a word(s) with jQuery使用 jQuery 实时突出显示一个单词
【发布时间】:2014-03-09 17:01:14
【问题描述】:

我想用 jQuery 突出显示单词。我使用实时 keyup 事件来触发突出显示,以便在输入单词时突出显示发生变化(为此使用输入文本字段)

我找到了一段可以正常工作的代码,但这段代码不适用于实时 keyup 事件,因此它会包装第一个字母并停在那里。

这是我的 HTML:

<input type="text" id="input" name="input"/>
<div id="content-block"><p>lorem ip sum </p></div>

这是我的 JS:

$('#input').live('keyup', function() {
    $('#input').trigger('highLight');
});

$('#input').bind('highLight', function() {
    var o = {words:$('input[name="input"]').val()};
    highlight("content-block",  o);
});

function highlight(id, options) {

    var o = {
                words: '',
                caseSensitive: false,
                wordsOnly: true,
                template: '$1<span class="highlight">$2</span>$3'
            }, 
        pattern;

    $.extend(true, o, options || {});

    if (o.words.length == 0) { return; }
    pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', o.caseSensitive ? "" : "ig");

    $('#'+id).each(function() {

        var content = $(this).html();

        if (!content) return;
        $(this).html(content.replace(pattern, o.template));

    });

}

【问题讨论】:

  • 请查看我的更新答案以获得解决方案,而不仅仅是问题的识别。

标签: javascript jquery highlighting


【解决方案1】:

问题是,在第一次成功替换后,模式现在还必须匹配在第一个匹配字符之后插入的结束 span 标记。

输入“l”后的HTML如下:

<p><span class="highlight">l</span>orem ip sum</p>

“lorem”将不再匹配,因为跨度。

现在有了解决方案:

这是一个应该让它做你想做的修复:

$('#' + id).each(function() {
    $('span.highlight',this).replaceWith($('span.highlight',this).text()); // Fix

    var content = $(this).html();

    if (!content) return;
    $(this).html(content.replace(pattern, o.template));
});

假设您只有一个突出显示跨度,下面的行将删除跨度并将其替换为其中包含的文本。然后替换正常进行。

$('span.highlight',this).replaceWith($('span.highlight',this).text()

这里有一个工作示例:http://jsfiddle.net/ryanrolds/N4DCR/

【讨论】:

  • 您的解决方案不适用于同一段落中的多个突出显示,如pointed here 和转载here(搜索ip,仅突出显示最后一个单词)。也许修复对其他用户有用。
  • 这正是我正在寻找的。但是,如果您将

    复制到小提琴中的

    ,您会看到一个错误,其中突出显示的字符被复制。有更新的机会吗? :-)
【解决方案2】:

即使您处于区分大小写模式,您也应该为您的正则表达式指定全局标志。这可能就是为什么只有第一个字符被替换的原因。试试这个:

pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', (o.caseSensitive ? "" : "i") + "g");

【讨论】:

  • 仍然包裹第一个字母,我看到我的示例代码已被编辑并且缺少一些部分......
  • 很抱歉,为了便于阅读,正在对其进行格式化...应该尽快修复。
猜你喜欢
  • 2010-09-12
  • 2014-03-16
  • 2013-02-23
  • 2015-10-14
  • 2014-09-12
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多