sac*_*een 104
这就是我在项目中的表现:
在HTML中定义模板:
<script type="text/template" id="cardTemplate">
<div>
<a href="{0}">{1}</a>
</div>
</script>
Run Code Online (Sandbox Code Playgroud)
使用string.format替换变量:
var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);
Run Code Online (Sandbox Code Playgroud)
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
Run Code Online (Sandbox Code Playgroud)
非常简单,您甚至可以组合模板.
模板一直比尝试手动解析JSON容易得多.由于我做出了贡献,我偏爱json2html,因为它不需要编译模板,只使用JSON和JavaScript.
| 归档时间: |
|
| 查看次数: |
64734 次 |
| 最近记录: |