html模板标签和jquery

jay*_*del 13 html jquery templatetag html5-template

我有这种情况,我正在尝试<template>在我的html源代码中使用该标记:

<template id="some-id">
  <div id="content-container">
    <span>{{some_string}}</span>
  <div>
</template>
Run Code Online (Sandbox Code Playgroud)

这最终将模板放在文档中,但不认为它在DOM中.这意味着在支持模板标记的浏览器中找不到$("#content-container").如果我搜索:

$("#some-id")
Run Code Online (Sandbox Code Playgroud)

我得到了回报:

<template id=?"some-id">?
  #document-fragment
    <div id="content-container">
      <span>{{some_string}}</span>
    <div>
</template>?
Run Code Online (Sandbox Code Playgroud)

这些都不会让我感到惊讶.我需要知道的是克隆文档片段的内容并拥有一个新节点,然后我可以将其放在我想要的DOM中.

我已经找到了如何使用jQuery实现这一点的示例,但是围绕这些内容的大部分代码已经在使用jQuery,我需要知道如何使用jQuery来执行此操作.

我的第一个想法是获取html,然后使用它来创建一个新节点:

stuff = $("#some-id").html()
new_node = $(stuff)
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

Error: Syntax error, unrecognized expression: <the html string>
Run Code Online (Sandbox Code Playgroud)

我不知道错误是否是由胡子语法引起的.我认为必须有一个jQuery解决方案来解决这个问题,但是当我用Google搜索时,我得到了jQuery模板的大量命中,这是不同的.

有没有人有想法,答案或指向网站/页面的指针,可以帮助我完成这项工作?我试图避免拼凑一些hackish.

编辑:我最终找到了这个解决方案(我还在测试它,以确保它是一个解决方案,但它看起来很有希望);

template = $("#some-id")
content = template.html()
new_div = $("<div></div>")
new_div.html(content)
Run Code Online (Sandbox Code Playgroud)

我最终得到了我以前不需要的div,但我可以忍受.但这种感觉很糟糕.有没有人有更好的方法呢?好处是它仍然可以在尚未完全适应模板标签行为的浏览器中运行.

谢谢!

HaN*_*riX 20

尝试:

var myTemplate = $("#some-id").html().trim();
var myTemplateClone = $(myTemplate);
Run Code Online (Sandbox Code Playgroud)

  • 不需要`trim()`。它什么也没做。 (2认同)

dtr*_*ers 8

我相信这个网站将有助于解释影子dom如何工作以及模板如何与它们互动. http://robdodson.me/blog/2013/08/27/shadow-dom-the-basics/

此外,克隆阴影模板的节点实际上非常简单,甚至不需要使用jquery.

这是一个演示它的jfiddle:http://jsfiddle.net/dtracers/fhWc3/1/

HTML:

<div id = "hoster">
    <span class = "title">Title</span>
    <span class = "id">51ab89af</span>
</div>

<template id = "im-a-template">
    <h1><content select =".title"></content></h1>
    <h1>Class Id: <content select = ".id"></content></h1>
    <input type="text" placeholder = "Name"></input>  
</template>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

// find where you want to put your shadow dom in
var host = document.querySelector('#hoster');

var root = host.createShadowRoot(); // create the host root

var template = document.querySelector('#im-a-template');

// this is the node of the object you wanted
var documentFragment = template.content;

// this is a cloned version of the object that you can use anywhere.
var templateClone = documentFragment.cloneNode(true);

root.appendChild(templateClone); // this empty root now has your template
Run Code Online (Sandbox Code Playgroud)

  • 这是内容标签的不同用途,与那里解释的不同。http://www.html5rocks.com/en/tutorials/webcomponents/template/ content标签用于将shadow root外部的信息投影到shadow root内部的数据 (2认同)