码迷,mamicode.com
首页 > Web开发 > 详细

script简单html模板实现

时间:2018-02-11 10:39:13      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:replace   val   instance   container   typeof   tom   containe   func   nta   

<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>

 

script简单html模板实现

标签:replace   val   instance   container   typeof   tom   containe   func   nta   

原文地址:https://www.cnblogs.com/lay2017/p/8440102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!