在 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)
这是输出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)
另一种方法是通过以下方式添加 HTML 字符串innerHTML
财产。
temp.innerHTML = '<div><h1>Hello</h1></div>'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)