我在jQuery代码中有一些超文本标记语言模板,我使用它们在JS中生成一些新元素。目前,我将它们放在页面的底部
<script type="text/html" id="ID_to_refer_from_jQuery">...HTML code here...</script>
我觉得这不是最好的方法,因为它们中的一些非常大,有没有办法将字符串HTML模板存储在HTML文件之外?
发布于 2016-06-03 05:24:55
最好的方法是使用HTML5 template feature,但不幸的是Internet Explorer10或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('');
如果你有一大块超文本标记语言,甚至会有an online tool自动将其格式化为JavaScript变量。
https://stackoverflow.com/questions/37602325
复制相似问题