如何在javascript中包围文本部分的范围?

时间:2008-11-18 21:03:54

标签: javascript jquery dom

我有这样的标记:

<p>one two three four</p>

我想使用javascript将其转换为:

<p>one <span>two three<span> four</p>

我想要在一个范围内包含的部分的偏移量和长度,在本例中为offset = 4length = 9。如果使用jQuery可以使它更容易,那就更好了。

1 个答案:

答案 0 :(得分:4)

这不是 Highlight a word with jQuery 问题的重复吗?

JQuery search highlight plugin之类的内容可能会有所帮助

或者,作为pointed out in the same question,编写自己的jquery函数:
像(未经测试的代码,随意编辑):

jQuery.fn.addSpan = function (elName, str, offset, length)
{
    if(this.innerHTML = str)
    {
        return this.each(function ()
        {
            this.innerHTML = this.innerHTML.substring(0,offset) + "<span>" + this.innerHTML.substring(offset, offset+length) + "</span>" + this.innerHTML.substring(offset+length));
        });
    }
};

你会像这样使用它:

$("p").addSpan("one two three four", 4, 9);
相关问题