Kev*_*Bot 1 html javascript documentfragment html5-template
我在 DocumentFragment 内部工作,并试图将 HTML 插入其中。我们知道 DocumentFragment 没有innerHTML setter,所以我尝试在DocumentFragment 中插入一个临时节点并在它之后使用 .html 插入HTML insertAdjacentHTML。然后我会删除临时元素,并留下一个带有我想要的 DOM 的片段。
示例:(错误是故意的)
var fragment = document.createDocumentFragment();
var temporaryElement = fragment.appendChild(document.createElement('div'));
// Before we move on.. I can see that the `temporaryElement` does have a parent
console.log(temporaryElement.parentNode.nodeType);
// The following throws an error...
temporaryElement.insertAdjacentHTML('afterend', '<div>Some crazy custom HTML..</div>');
fragment.removeChild(temporaryElement);Run Code Online (Sandbox Code Playgroud)
我可以清楚地看到临时元素有一个 parentNode,那么为什么会出现这个错误呢?
你可以:
<template>元素,innerHTML属性添加字符串内容,content属性中获取 DocumentFragment 。//Use a template
var template = document.createElement( 'template' )
template.innerHTML = '<td>Hello<td>World'
//Get the document fragment
var fragment = template.content
Row.appendChild( fragment )Run Code Online (Sandbox Code Playgroud)
<table>
<tr id=Row></tr>
</table>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3354 次 |
| 最近记录: |