我有这样的标记:
<p>one two three four</p>
我希望使用JavaScript将其转换为以下内容:
<p>one <span>two three<span> four</p>
我有想要用span标签包裹的部分的偏移量和长度,例如在这种情况下offset = 4
和length = 9
。如果使用jQuery可以使它更容易,那就更好了。
我有这样的标记:
<p>one two three four</p>
我希望使用JavaScript将其转换为以下内容:
<p>one <span>two three<span> four</p>
我有想要用span标签包裹的部分的偏移量和长度,例如在这种情况下offset = 4
和length = 9
。如果使用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);