无法从模板获取内容

编程入门 行业动态 更新时间:2024-10-13 16:20:47
本文介绍了无法从模板获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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>'

更多推荐

无法从模板获取内容

本文发布于:2023-11-25 23:12:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631730.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   内容

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!