【问题标题】:Nesting HTML5 <template> tag嵌套 HTML5 <template> 标签
【发布时间】:2015-09-11 04:02:31
【问题描述】:

HTML5 Rocks 确实说我可以嵌套模板。但是当我使用它们时,如下所示,它们不会渲染。

<template id ='#outer'>
  <ul>
    <template = '#inner'>
      <li>Stuff</li>
    </template>
  </ul>
</template>

但是,以下工作:

<template id ='#outer'>
  <p>hi</p>
    <template = '#inner'>
      <p>there</p>
    </template>
</template>
<div id="tDiv">

</div>      

    var outer = document.querySelector('#outer');
    var outerClone = outer.content.cloneNode(true);
    var check = outerClone.querySelector('template');
    var innerClone = check.content.cloneNode(true);
    var tDiv = document.querySelector('#temp');
    tDiv.appendChild(innerClone);

但是通过这种方式,我可以使用innerCloneouterClone 并打个招呼。不嗨。

我无法理解为什么模板是嵌套的而不是独立使用的真正目的。嵌套模板不会使事情复杂化吗?

【问题讨论】:

  • 这个问题是否与 Polymer 网络组件有关?
  • 一般来说只是 HTML5

标签: html templates polymer web-component html5-template


【解决方案1】:

正如 HTML5Rocks 教程中使用模板的陷阱中提到的那样:

激活外部模板不会激活内部模板。那是 也就是说,嵌套模板要求他们的孩子也手动 已激活。

即使我忽略了&lt;template = '#inner'&gt; 中的拼写错误并假设它是&lt;template id='inner'&gt;,我认为您必须在每个模板上单独调用document.importNode(template.content, true),然后使用它。在您的示例中,您只是将 outerClone 附加到仍然包含惰性内部模板的 DOM。您需要将激活的内部模板内容附加到外部模板以使它们都呈现。

jsfiddle 是实现这一目标的一种方式。

【讨论】:

    【解决方案2】:

    为了获得一个你好,你必须创建一个完整的克隆选择器树(即outerCloneinnerClone),并将其附加到可见的选择器(@ 987654324@) (模板不可见)

    <template id ='#outer'>
      <p>hi</p>
        <template id = '#inner'> // mind the *id* !!
          <p>there</p>
        </template>
    </template>
    <div id="tDiv">
    
    </div>  
    
    var outer = document.querySelector('#outer');
    var outerClone = outer.content.cloneNode(true);
    var check = outerClone.querySelector('#inner'); //mind #inner here
    var innerClone = check.content.cloneNode(true);
    outerClone.appendChild(innerClone);             //append inner to outer
    var tDiv = document.querySelector('#temp');
    tDiv.appendChild(outerClone);                   //append outer
    

    这里是jsfiddle,代码正在运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2011-06-03
      • 2011-04-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多