Template控件

   看了一下Microsoft的一个Template的JQuery插件,总是感觉使用起来特别别扭,我还是自己写一个吧。代码如下:

(function($) {

    $.fn.template = function(tmpl, arrayData) {

        if ($.isArray(arrayData) && tmpl) {

            var pReg = /\$\{\s*[a-zA-Z]+(\.[a-zA-Z]+)*\s*\}/g;

            var places = tmpl.match(pReg);

            var props = new Array();

            for (var i = 0; i < places.length; i++) {

                props.push($.trim(places[i].substr(2, places[i].length - 3)));

            }

            for (var j = 0; j < arrayData.length; j++) {

                var item = arrayData[j];

                var htmlItem = tmpl;

                for (var k = 0; k < places.length; k++) {

                    (function(r, p, d) {

                        htmlItem = htmlItem.replace(r, (function(prop, data) {

                        var path = prop.split(/\./g);

                            var count = 0;

                            for (var l = 0; l < path.length; l++) {

                                if (data.hasOwnProperty(path[l])) {

                                    data = data[path[l]];

                                    count++;

                                }

                                else {

                                    break;

                                }

                            }

                            if (count == path.length) {

                                return data;

                            }

                            else {

                                return "";

                            }

                        })(p, d));

                    })(places[k], props[k], item);

                }

                this.append(htmlItem);

            }

        }
return this; } })(jQuery);

使用示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

    <title>模板控件测试</title>

    <link href="Style/site.css" rel="stylesheet" type="text/css" />

    <script src="Script/jquery.js" type="text/javascript"></script>

    <script src="Script/JTemplate.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function() {

        $("#content").template("<tr style='height:30px;'><td>${Name}</td><td>${ Age}</td><td>${ Adress.Street}</td></tr>", [{ Name: "zhoulq", Age: 28, Adress: { Street: "BaoAn", Road: 1} }, { Name: "sunyd", Age: 23, Adress: { Street: "FengXian", Road: 2} }, { Name: "yangql", Age: 24, Adress: { Street: "HuaGuang", Road: 4}}]);

        });

    </script>

</head>

<body>

<table id="content" class="dgMain">

<tr class="dgHeader" style="height:30px;"><th>姓名</th><th>年龄</th><th>街道</th></tr>

</table>

</body>

</html>


 

你可能感兴趣的:(template)