我有一个脚本来围绕选择包装html标签。
function wrap(tagName)
{
var selection;
var elements = [];
var ranges = [];
var rangeCount = 0;
if (window.getSelection)
{
selection = window.getSelection();
if (selection.rangeCount)
{
rangeCount = selection.rangeCount;
for (var i=0; i<rangeCount; i++)
{
ranges[i] = selection.getRangeAt(i).cloneRange();
elements[i] = document.createElement(tagName);
elements[i].appendChild(ranges[i].cloneContents());
ranges[i].deleteContents();
ranges[i].insertNode(elements[i]);
ranges[i].selectNode(elements[i]);
}
selection.removeAllRanges();
for (var i=0; i<ranges.length; i++)
{
selection.addRange(ranges[i]);
}
}
}
}
它工作正常,但当我尝试选择以下文本并围绕以下代码包装标签时
<strong>W</strong>elcom<strong>e</strong>
代码更改为
<strong></strong><u><strong>W</strong>elcom<strong>e</strong></u><strong></strong>
而不是
<u><strong>W</strong>elcom<strong>e</strong></u>
我用firebug检查了代码,但在函数deleteContents()
出错了。函数deleteContents()留下两个空节点<strong></strong>
,因此它不会删除整个内容。这是怎么发生的?