代码之家  ›  专栏  ›  技术社区  ›  Christian Oudard

如何在javascript中围绕一段文本换行?

  •  2
  • Christian Oudard  · 技术社区  · 16 年前

    我有这样的标记:

    <p>one two three four</p>
    

    我想用javascript把它转换成:

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

    在这种情况下,我得到了要在跨度中包装的截面的偏移量和长度。 offset = 4 length = 9 . 如果使用jquery可以使它更容易,那就更好了。

    1 回复  |  直到 16 年前
        1
  •  4
  •   Community kfsone    7 年前

    这不是问题的一点重复吗 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);