Skip to main content

模板引擎

DOM2JSON

<div>
<span>
<a></a>
</span>
<span>
<a></a>
<a></a>
</span>
</div>

把上诉 dom 结构转成下面的 JSON 格式

{
tag: 'DIV',
children: [
{
tag: 'SPAN',
children: [
{ tag: 'A', children: [] }
]
},
{
tag: 'SPAN',
children: [
{ tag: 'A', children: [] },
{ tag: 'A', children: [] }
]
}
]
}
function dom2Json(domtree) {
let obj = {};
obj.name = domtree.tagName;
obj.children = [];
domtree.childNodes.forEach((child) => obj.children.push(dom2Json(child)));
return obj;
}

实现一个极简的模板引擎