这个是承接上一篇写的,算是对上一篇的扩展 Javascript字符串模板简单实现(一)
下面是html,看到这里,大概已经知道要做什么了吧。
<div id="container"></div>
<script type="text/html" id='template'>
<h2>标题:{{title}}</h2>
<h2>颜色:{{color}}</h2>
<h2>内容:{{content}}</h2>
<h2>姓名:{{name}}</h2>
</script>
script
标签中的type="text/html"
:定义一个被JS调用的代码,但是代码不会在页面上显示
下面是我们要的最终结果:
<div id="container">
<h2>标题:1</h2>
<h2>颜色:black</h2>
<h2>内容:我是内容</h2>
<h2>姓名:admin</h2>
</div>
直接上javascript:
function fun() {
var tpl = document.getElementById(arguments[0]).innerHTML;
var data = arguments[1];
var exp = /\{\{(\w+)\}\}/g;
while((result = exp.exec(tpl)) != null){
if(result[1]){
tpl = tpl.replace(result[0],data[result[1]]);
}
}
return tpl;
}
var res = fun('template',{
title:'1',
color:'black',
content:'我是内容',
name:'admin'
});
document.getElementById('container').innerHTML = res;
浏览器运行结果如下:
标题:1
颜色:black
内容:我是内容
姓名:admin