<html> <head> <title>text/html demo</title> </head> <style type="text/css"> .template{ border-bottom: 1px solid black; } </style> <body> <div id="container"></div> <!-- 模板 --> <script type="text/html" id="template"> <div class="template">名字:{{name}}</div> <div class="template">年龄:{{age}}</div> </script> <script type="text/javascript"> var Person = function(name, age){ this.name = name; this.age = age; } var persons = [new Person(‘lay‘, 23), new Person(‘marry‘, 24)] var render = function(html, data){ if (data instanceof Array) { var tpl = html; html = ""; for (var i = 0; i < data.length; i++) { var item = data[i]; var template = tpl; var newHtml = getHtml(template, item); html += newHtml; }; } else if (typeof(data) == ‘object‘ ) { html = getHtml(html, data); }; return html; } var getHtml = function(html, data){ var arr = html.match(/{{[a-zA-Z0-9]+}}/g); for (var i = 0; i < arr.length; i++) { var item = arr[i]; var fieldName = item.replace(/{{/g, ‘‘).replace(/}}/g, ‘‘); var value = data[fieldName]; html = html.replace(item,value) }; return html; } var template = document.getElementById("template"); var container = document.getElementById("container"); container.innerHTML = render(template.innerHTML, persons); </script> </body> </html>