5

我正在将 textnodes 添加到 documentFragment 中,如下所示:

var foo = document.createDocumentFragment();
var someText = "Hello World";
foo.appendChild(document.createTextNode(someText));

这工作正常,但有时我被传递“文本”,其中包括这样的内联链接:

var someOtherText = "Hello <a href='www.world.com'>World</a>";

在我的处理程序中,它被转换为硬编码文本而不是链接。

问题:
如何将上述 HTML 字符串附加到 documentFragment 中?如果我不使用textNodes,可以使用appendChild吗?

4

3 回答 3

12

创建一个临时 div,在 innerHTML 中插入文本,然后将 div 的所有节点移动到片段中。由于一个元素一次只能在一个地方,它会自动从临时 div-tag 中删除。

var frag = document.createDocumentFragment();

var div = document.createElement('div');
div.innerHTML = '<a href="http://stackoverflow.com/">Stack overflow</a>';
while (div.firstChild) frag.appendChild(div.firstChild);
于 2013-11-12T13:03:15.160 回答
5
document.createRange().createContextualFragment("<span>Hello World!</span>");

它返回一个 DocumentFragment。

支持 IE >= 9

编辑:

最近版本的Safari似乎因捷径而失败,这里有一点长但有效的方法:

var range = document.createRange();
range.selectNode(document.body); // Select the body cause there is always one (documentElement fail...)

var fragment = range.createContextualFragment("<span>Hello World!</span>");
于 2015-12-15T15:07:09.150 回答
0

这可能有效:

var foo = document.createDocumentFragment();
var someText = 'Hello <a href="www.world.com">World</a>';
var item = document.createElement('span');
item.innerHTML = someText
foo.appendChild(item);
document.body.appendChild(foo);
于 2013-11-12T13:00:06.387 回答