如何使用& lt; script type =& quot;文本/模板& quot;& gt;创建嵌入的HTML模板使用jQuery

问题描述:

我想创建HTML模板,该模板可以使用脚本标签从jQuery调用,然后可以使用jQuery显示HTML.

I would like to create HTML templates that can be called form jQuery using script tags and then be able to show the HTML using jQuery.

<script type="text/template">
   <div id="new-post">
     <form>
       <label>Post Title</label>
       <input type="text" id="post-title"/>
       <input type="submit" value="Save"/>
     </form>
   </div>
</script>

我在*.com上找到了其他帖子,但这些都不是我想要的.任何有关如何使它工作的建议都将不胜感激.

I have found other post on *.com, but none are what I'm looking for. Any advice on how to get this working would be appreciated.

您尝试执行的操作应该可以.如果您有这样的事情:

What you're trying should work OK. If you have something like this:

<script type="text/html" id="post-template">
  <div id="new-post">
    <form>
      <label>Post Title</label>
      <input type="text" id="post-title"/>
      <input type="submit" value="Save"/>
    </form>
  </div>
</script>

您应该能够执行以下操作以提取模板:

You should be able to do this to extract the template:

var template = $('#post-template').html();

更好的是,使用jQuery模板.请参阅本文档以了解它们的工作原理.

Better yet, look into using jQuery templates. See this documentation for a good overview of how they work.