我试图使用客户端模板来实现这样的效果,下面就是改写后的实例:
demo 2:
运行代码框
看一下前后两个demo的区别:
demo1中的:
...
...
function getData(){
/*假设data就是用xmlhttp获取到的数据*/
var ph = document.getElementById('post_header');
var pt = document.getElementById('post_title');
var pc = document.getElementById('post_content');
ph.innerHTML = "("+data.id+")<a href='mailto:"+data.mail+"'>"+data.name+"</a>于"+data.time+"发表:";
pt.innerHTML = data.title;
pc.innerHTML = data.content;
}
...
...
<div id="post">
<fieldset>
<legend id="post_header">标题</legend>
<h4 id="post_title"></h4>
<p id="post_content"></p>
</fieldset>
</div>
...
...
demo2中的:
...
...
function getData(){
var p = document.getElementById('post');
var t = p.innerHTML;
t = t.replace(/<!--{(.*?)}-->/g,function(a,b){
var v = "";
try{
v = eval("data."+b);
}
catch(e){}
return v;
});
p.innerHTML = t;
}
...
...
<div id="post">
<fieldset>
<legend id="post_header">(<!--{id}-->)<a href='mailto:<!--{mail}-->'><!--{name}--></a>于<!--{time}-->发表:</legend>
<h4 id="post_title"><!--{title}--></h4>
<p id="post_content"><!--{content}--></p>
</fieldset>
...
...
看到区别了吗?我的模板实现和传统的ajax实现不同,我是将数据的结构从js中抽取出来,提前嵌入到html代码中(我用<!--{...}-->来代表模板信息),从而做到降低js代码中代码与页面结构的耦合。