I have markup like this:
我有这样的标记:
<p>one two three four</p>
And I want to use javascript to convert it to this:
我想用javascript将其转换为:
<p>one <span>two three<span> four</p>
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.
我有一个我希望在一个span中包装的部分的偏移量和长度,在这种情况下offset = 4和length = 9.如果使用jQuery可以使它更容易,那就更好了。
1 个解决方案
#1
4
Is this not a little duplicate of the question Highlight a word with jQuery ?
这不是一个问题的重复吗?用jQuery突出显示一个单词?
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函数:像(未经测试的代码,随意编辑):
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));
});
}
};
And you would use it like so:
你会像这样使用它:
$("p").addSpan("one two three four", 4, 9);
#1
4
Is this not a little duplicate of the question Highlight a word with jQuery ?
这不是一个问题的重复吗?用jQuery突出显示一个单词?
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函数:像(未经测试的代码,随意编辑):
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));
});
}
};
And you would use it like so:
你会像这样使用它:
$("p").addSpan("one two three four", 4, 9);