JS使用正则+JSON对HTML模板进行数据填充

来源:互联网 发布:知乎周刊plus epub 编辑:程序博客网 时间:2024/06/05 11:22


 <style>
        ul, li {
            list-style: none;
        }


        .container {
            width: 200px;
            margin: 20px auto;
            padding: 5px;
            background-color: #1B6540;
        }


        .list_box li {
            color: #fff;
            height: 60px;
            margin-bottom: 5px;
            background-color: #4FA46B;
        }
    </style>






    <div class="container">
        <ul class="list_box" id="list_box">
            <script type="text/template" data-number="list_tple">
                <li class="list_item">
                    {#  $title$  之间的字符串表示json的key                  #}
                    <p>$content$</p>
                    <h3>$title$</h3>
                </li>
            </script>
        </ul>
    </div>




 <script>
        json_data = {
            page: "1",
            records: "3",
            data: [{
                title: "标题1",
                content: "内容1"
            }, {
                title: "标题2",
                content: "内容2"
            }, {
                title: "标题3",
                content: "内容3"
            }, {
                title: "标题4",
                content: "内容4"
            }, {
                title: "标题5",
                content: "内容5"
            },]
        }
        String.prototype.tmple = function (obj) {
            //  '/'  一般用于 正则的开始和结束,中途要使用/就得用\符号来转义了,
            //  '\$'  我猜想是值 $$ 之间的东西
            //  '\w+'  匹配任何字类字符,包括下划线。与“[A-Za-z0-9_]”等效。
            //  '/g'  意思就是:global可选标志,带这个标志表示替换将针对行中每个匹配的串进行,否则则只替换行中第一个匹配串
            return this.replace(/\$\w+\$/g, function (matchs) {
                var returns = obj[matchs.replace(/\$/g, "")];
                return (returns + "") == "undefined" ? "" : returns;
            });
        };


        //使用 data-* 属性来嵌入自定义数据: 这个用的是id


        var htmlList = '',
                htmlTemp = $("#list_box script[data-number='list_tple']").html();
        json_data.data.forEach(function (object) {
            // tmple 这里指正则表达式
            htmlList += htmlTemp.tmple(object);
        });
        $("#list_box").html(htmlList);
    </script>
原创粉丝点击