问题描述:
实现目前一些主流框架的循环渲染
// ali-for
var items = [
{name:'item1'},
{name:'item2'}
];
var str = '<div ali-for="item in items">{{item.name}}<div>';
var ParseDom = function(str){
// your code here
}
// 对应生成的dom
// <div>item1</div>
// <div>item2</div>
程序如下:
var ParseDom = function(str){
// your code here
var reg1 = /\sali-for=\"[a-zA-Z\s]+\"/gi, //获得 ali-for="item in items"
reg2 = /\{{2}[a-zA-Z\.]+\}{2}/gi, //获得{{item.name}}
reg3 = /\.[a-zA-Z]+/gi, //获得.name
len = items.length
var temp = str.replace(reg1,''), //tmp = '<div>{{item.name}}</div>'
fill = str.match(reg2)[0], //fill = "{{item.name}}"
key = str.match(reg2)[0].match(reg3)[0].slice(1), //key = "name"
clone_temp = '',
str = ''
for(var i=0;i<len;i++){
clone_temp = temp
st r+= clone_temp.replace(fill,items[i][key])
}
console.log(str)
}