布局结构:
html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./js/my.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/html" id="tpl-user">
<div>姓名:{{name}}</div>
<div>年龄:{{age}}</div>
<div>性别:{{sex}}</div>
<div>地址:{{address}}</div>
</script>
<script>
var data={
name:'张三',
age:18,
sex:'男',
address:'上海'
};
var htmlStr=template('tpl-user',data);
document.getElementById('container').innerHTML=htmlStr;
</script>
</body>
</html>
js文件
function template(id,data){
var str=document.getElementById(id).innerHTML;
var pattern=/{{\s*([a-zA-Z]+)\s*}}/;
while(pattern.exec(str)){
str=str.replace(pattern.exec(str)[0],data[pattern.exec(str)[1]]);
}
return str;
}