如何在JavaScript中的文字部分中绕一个跨度? [英] How do I wrap a span around a section of text in javascript?

查看:78
本文介绍了如何在JavaScript中的文字部分中绕一个跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的标记:

<p>one two three four</p>

我想使用javascript将其转换为:

And I want to use javascript to convert it to this:

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

我有一个偏移和长度的段要包装在一个跨度,在这种情况下 offset = 4 length = 9

I have the offset and length of the section I want to wrap in a span, in this case offset = 4 and length = 9. If using jQuery can make it easier, that is preferable.

推荐答案

这个问题与 < a href =https://stackoverflow.com/questions/119441>使用jQuery突出显示一个单词

Is this not a little duplicate of the question Highlight a word with jQuery ?

一个href =http://www.jquery.info/scripts/SearchHighlight/demo_en.html =nofollow noreferrer> JQuery search highlight plugin 可能会有帮助

Something like the JQuery search highlight plugin could be helpful

或者,像同一个问题中指出的那样,编写自己的jQuery函数:

某些东西(未经测试的代码,随意编辑):

Or, as pointed out in the same question, write your own jquery function:
Something like (untested code, feel free to edit):

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);

这篇关于如何在JavaScript中的文字部分中绕一个跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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