我将文本节点添加到这样的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来完成吗?
发布于 2013-11-12 13:03:15
创建一个临时div,在innerHTML中插入文本,然后将div的所有节点移动到片段中。由于一个元素一次只能出现在一个地方,所以它将自动从临时div-标记中删除。
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);发布于 2015-12-15 15:07:09
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>");发布于 2013-11-12 13:00:06
这可能是可行的:
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);https://stackoverflow.com/questions/19929641
复制相似问题