使用jQuery实时突出显示一个或多个单词 [英] live highlight a word(s) with jQuery

查看:86
本文介绍了使用jQuery实时突出显示一个或多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to live highlight words with jQuery. I use a live keyup event to trigger the highlighting, so that the highlighting changes upon entering words(using a input text field for this)

我找到了一段可以正常工作的代码,但是该代码不适用于实时keyup事件,因此它包装了第一个字母并在此停了下来.

I have found a piece of code which works fine but this code doesn't works with the live keyup event, so it wraps the first letter and stops there.

这是我的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));

    });

}

推荐答案

问题在于,第一次成功替换后,模式现在还必须匹配在第一个匹配字符之后插入的结尾span标签.

The issue is that after the first successful replace the pattern now has to also match the ending span tag that has been inserted after the first matched character.

输入"l"后,HTML如下所示:

The HTML looks like this after entering "l":

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

范围"不再匹配.

现在有解决方案:

这是一个修复程序,可以使它按您想要的方式工作:

Here is a fix that should get it doing what you want:

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

假设您只有一个突出显示范围,则下面的行将删除该范围并将其替换为包含的文本.然后替换将正常进行.

Assuming that you will only have a single highlight span, the line below removes the span and replaces it with the text that it contained. Then the replace happens as normal.

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

此处是一个工作示例: http://jsfiddle.net/ryanrolds/N4DCR/

A working example is here: http://jsfiddle.net/ryanrolds/N4DCR/

这篇关于使用jQuery实时突出显示一个或多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆