html - <script type="text/html">
其中 text/html 是 MIME(类似于扩展名)的一种。
姑且将 <script type='text/html'>
称之为 “html脚本” 吧。
这种脚本,通常作为代码模版使用。类似于短信模版、邮件模版,预置一些占位符。使用的时候,用实际数值替换占位符。
与 text/javascript 一样,不会直接在界面上打印这些内容,使用的时候,需要 javascript 读取、加工后使用。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<script type="text/javascript" src="../res/js/jquery.min.js"></script>
<body>
<input type="button" id="addFun" value="click me" onclick="loadHtml()" />
<!-- 父级容器 -->
<div id="comment_ul_2"> </div>
<!-- 一个代码模版,包含很多的占位符 -->
<script id="commentTemplate" type="text/html">
<li>
<div class="photo">
<a href="#">
<img src="{{UserImg}}" /></a></div>
<p>
<a href="#">{{UserName}}:</a>
<span class="time">{{CreateDate}}</span></p>
<div class="clear">
</div>
</li>
</script>
<script type="text/javascript">
function loadHtml() {
// 用于填充占位符的数值
var data={'UserImg':'aaaaa','UserName':'zhang','CreateDate':'2011-1-1'};
// 替换占位符之后,将代码追加到父级容器中
$("#comment_ul_2").append(template("commentTemplate",data));
}
// 替换占位符的函数
function template(cellId,data){
var reg = new RegExp("\\{\\{([^\\[\\]]*?)\\}\\}", 'igm');
var html = document.getElementById(cellId).innerHTML;
return html.replace(reg,
function (node, key) {
return data[key];
}
);
}
</script>
</body>
</html>
疯狂的妞妞 :每一天,做什么都好,不要什么都不做!