繁体   English   中英

如何在javascript中将一段文字环绕起来?

[英]How do I wrap a span around a section of text in javascript?

我有这样的标记:

<p>one two three four</p>

而且我想使用javascript将其转换为此:

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

我具有要在一个跨度中包装的部分的偏移量和长度,在这种情况下, offset = 4length = 9 如果使用jQuery可以使其更容易,那是可取的。

这不是问题的重复吗? 用jQuery突出显示一个单词

诸如JQuery搜索突出显示插件之类的功能可能会有所帮助

或者,如在同一问题中指出的那样 ,编写您自己的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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM