Home  >  Article  >  Web Front-end  >  javascript利用初始化数据装配模版的实现代码_javascript技巧

javascript利用初始化数据装配模版的实现代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:16:18784browse

var list = [{id:1, name:"czone", age:21}, {id:2, name:'czonechan', age:21}];
var template ='

$name$age
';

实现一个通用方法,使用初始化数据来装配模版。
复制代码 代码如下:

function displayTemplate(list,template){
var result="";
for(var i=0,l=list.length;ivar temp=template;
for(var k in list[i])
{
var reg=new RegExp("\\$"+k,"g");
temp=temp.replace(reg,function(w){
return list[i][k];
})
}
result+=temp;
}
return result;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn