【问题标题】:Cannot get content from template无法从模板中获取内容
【发布时间】:2017-09-16 10:01:51
【问题描述】:

在 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 的输出:

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

【问题讨论】:

  • div 被“剥离”了,因为 appendChild 函数返回子元素 (h1) 而不是父元素 (div)。
  • @Titus 好吧。我以为我将孩子附加到div,然后返回div。感谢您指出这一点。

标签: javascript html web-component html5-template


【解决方案1】:

创建<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)

另一种方法是通过 innerHTML 属性添加 HTML 字符串。

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

【讨论】:

    【解决方案2】:

    注意,var div = document.createElement('div').appendChild(h1)div 变量设置为h1,附加元素,而不是div 元素;见What is the behavior of document.createElement when passed as an argument?

    &lt;template&gt;.innerHTML 设置为div 元素的.outerHTML,调用链接到document.body.appendChild(),并将temp.content 作为参数。

    window.onload = function() {
    
      var temp = document.createElement('template');
      var h1 = document.createElement('h1');
      h1.textContent = 'hello';
    
      var div = document.createElement('div');
      div.appendChild(h1);
      temp.innerHTML = div.outerHTML;
    
      console.log('temp: ', temp.content);
    
      document.body.appendChild(temp.content);
    
    }
    &lt;body&gt;&lt;/body&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多