无法从模板获取内容 [英] Cannot get content from template

查看:68
本文介绍了无法从模板获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我试图动态创建HTML <template>元素,将<h1>元素作为其子元素,克隆模板的内容,然后将模板附加到文档主体.

In Javascript, I am trying to dynamically create an HTML <template> element, append an <h1> element as its child, clone the template's contents, and then append the template to the document body.

问题是,当我访问模板的content属性时,它仅返回#document-fragment.

The problem is when I access the content property of the template it just returns #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的输出:

我在这里做错了什么?为什么模板的内容显示为空?

What am I doing wrong here? Why is the template's contents showing up as empty?

推荐答案

创建<template>时,应将DOM内容(带有appendChild())附加到.content属性(它是DocumentFragment)上,而不是元素本身.

When you create a <template>, you should append DOM content (with appendChild()) to the .content property (which is a DocumentFragment), not to the element itself.

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)

一种替代方法是通过innerHTML属性添加HTML字符串.

An alternative is to add a HTML string via the innerHTML property.

temp.innerHTML = '<div><h1>Hello</h1></div>'

这篇关于无法从模板获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆