Gra*_*ham 2 html javascript web-component html5-template
在 Javascript 中,我试图动态创建一个 HTML<template>元素,附加一个<h1>元素作为其子元素,克隆模板的内容,然后将模板附加到文档正文。
问题是当我访问content模板的属性时它只是返回#document-fragment。
这是代码:
var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';
var div = document.createElement('div').appendChild(h1)
temp.appendChild(div)
console.log('temp: ', temp)
console.log('temp content: ', temp.content)
var c = document.importNode(temp.content, true)
document.body.appendChild(c)
Run Code Online (Sandbox Code Playgroud)
这是输出console.log's:
我在这里做错了什么?为什么模板的内容显示为空?
创建 时<template>,您应该将 DOM 内容(带有appendChild())附加到.content属性(这是一个 DocumentFragment),而不是附加到元素本身。
var temp = document.createElement('template');
var h1 = document.createElement('h1');
h1.textContent = 'hello';
var div = document.createElement('div')
div.appendChild(h1)
//append DOM to .content
temp.content.appendChild(div)
console.log('temp: ', temp)
console.log('temp content: ', temp.content)
var c = document.importNode(temp.content, true)
document.body.appendChild(c)Run Code Online (Sandbox Code Playgroud)
另一种方法是通过属性添加 HTML 字符串innerHTML。
temp.innerHTML = '<div><h1>Hello</h1></div>'
Run Code Online (Sandbox Code Playgroud)