2016-06-14 52 views
4

我有一段HTML代码,我想在整个页面中重复使用。创建未被浏览器解析的HTML代码(供重用)

 <div class="gmail-message-container"> 
      <span class="trim-text"> 
       <span class="gmail-sender"> 
        [email protected] (Some Name) 
       </span>: 
      </span> 
      <br> 
      <b><span class="trim-text gmail-title">Some title</span></b> 
      <br> 
      <span class="trim-text gmail-summary">Some summary text goes here</span> 
     </div> 

我怎样才能让gmail-message-container作为一个没有被显示,并可以由JavaScript来抓住并添加到多个地方html元素?

元素被分配了某些CSS规则,这些规则会根据容器内部元素的数量来影响元素,因此我不能仅仅执行display: none;,因为它会计入我尝试复制的元素中。

+0

@apokryfos仔细看问题:“我不能只显示:无;“ – beerwin

+0

在容器中做'style ='display:none;''。不要让自己难过。 – apokryfos

+0

您可能需要考虑模板引擎,例如http://handlebarsjs.com/或https://github.com/janl/mustache.js –

回答

8

用于上述目的的通用模式是使用

<script type="text/template" id="template"> 
// your html goes here 
</script> 

text/template防止浏览器解析<script>标签的内部(你可以使用不同的东西,它只是要求不使用text/javascript这样做)

您可以通过使用document.getElementById('template').innerHTML

+1

这似乎是一种解决许多其他问题的方法。谢谢! –

4

您可以将它放在script标记中。

<script id="your-template-id" type="text/template"> 
    <div class="gmail-message-container"> 
     ....  
    </div> 
</script> 

浏览器不知道什么类型的text/template手段,不解析它。 您可以通过这个ID模板的抢内容之后,例如:

var tpl = document.querySelector('#your-template-id').innerHTML; 

这种形式给出在某些JS框架中使用,如Backbone

====

还有html5标签template,您可以使用,它是明确设计为容纳模板。

3

一个可能的解决方案后抢你的模板:

将其放置在容器外部的一个隐藏的DIV,它有一个ID:

<div id="message_template" style="display:none"> 
    <div class="gmail-message-container"> 
     <span class="trim-text"> 
      <span class="gmail-sender"> 
       [email protected] (Some Name) 
      </span>: 
     </span> 
     <br> 
     <b><span class="trim-text gmail-title">Some title</span></b> 
     <br> 
     <span class="trim-text gmail-summary">Some summary text goes here</span> 
    </div> 
</div> 

然后使用JavaScript来隐藏div的内容复制到您的容器。

JQuery的溶液:

var newItem = $("#message_template").find(".gmail-message-container").clone(); 

newItem.appendTo($("yourcontainer")); 

其中yourcontainer是将具有.gmail-message-container物品容器的选择器。

另一种解决方案,非常类似于上面的一个,是将其指定为模板:

指定您的片段作为模板:

<script type="text/html" id="your-template-name"> 
    <div class="gmail-message-container"> 
     <span class="trim-text"> 
      <span class="gmail-sender"> 
       [email protected] (Some Name) 
      </span>: 
     </span> 
     <br> 
     <b><span class="trim-text gmail-title">Some title</span></b> 
     <br> 
     <span class="trim-text gmail-summary">Some summary text goes here</span> 
    </div> 
</script> 

var template = document.querySelector('#your-template-name').innerHTML;