我想知道是否可以使用单个文档片断在DOM中插入多个片断,还是必须为每个要插入的元素创建新的片断。
我可以做下面的例子吗:
var frag = document.createDocumentFragment(),
div = document.createElement('div'),
section = document.createElement('section'),
header = document.createElement('header'),
divFrag = frag.appendChild(div),
sectionFrag = frag.appendChild(section),
headFrag = frag.appendChild(header);非常感谢
发布于 2011-08-17 23:52:49
只需注意一下代码:appendChild返回插入的DOM元素,因此:
divFrag = frag.appendChild(div)将返回div。即div === divFrag。
要回答您的问题,您可以重用文档片段。
例如,如果您想要将所有元素附加到<body>,您可以这样做:
frag.appendChild(div);
frag.appendChild(section);
frag.appendChild(header);
document.body.appendChild(frag); // append all three elems at once to the body
// frag is now an empty fragment, ready for re-usehttps://stackoverflow.com/questions/7095723
复制相似问题