我应该在哪里存储 js 模板



我在jQuery代码中有一些HTML模板,我用它们用JS生成一些新元素。目前,我将它们保留在页面底部

<script type="text/html" id="ID_to_refer_from_jQuery">...HTML code here...</script>

我觉得这不是最好的方法,因为其中一些非常大,有没有办法将字符串 HTML 模板存储在 HTML 文件之外?

将它们放在另一个文件夹中,然后使用 AJAX 调用它们。你不想有一个大文件。相反,利用组织文件夹系统来保持项目井井有条。

示例文件夹结构

/root
  index.html
  /templates
    navigation.html
    footer.html
    ... 

加载它们

$("header").load("templates/navigation.html");

最好的方法是使用 HTML5 模板功能,但不幸的是,Internet Explorer 10 或 11 不支持它。以下是使用它的示例:

<template id="simple">
    <style>
        span { color: purple; }
    </style>
    <img src="http://placehold.it/50x50" />
    <span>Hello World!</span>
    <script>
        function boom(){
            alert("BOOM!");
        }
        boom();
    </script>
</template>

 

function addSimple(){
    // Grab our template
    var t = document.querySelector('template#simple').content;
    // Optional -- Modify template
    // Clone and add
    var clone = document.importNode(t, true);
    document.getElementById("simple-target").appendChild(clone);
}

(本示例来源)


与此同时,我见过的最常见的方法是将HTML放在JavaScript变量中,如下所示:

var html = [
'<div>',
'    <h1>Example Domain</h1>',
'    <p>This domain is established to be used for illustrative examples in documents. You may use this',
'    domain in examples without prior coordination or asking for permission.</p>',
'    <p><a href="http://www.iana.org/domains/example">More information...</a></p>',
'</div>'
].join('');

如果你有一大块HTML,甚至还有一个在线工具会自动将其格式化为JavaScript变量。

最新更新