JS使用模板快速填充HTML控件數據

function formatTemplate(dta, tmpl) {  
    var format = {  
        name: function(x) {  
            return x ; 
        }  
    };  
    return tmpl.replace(/{(\w+)}/g, function(m1, m2) {  
        if (!m2)  
            return "";  
        return (format && format[m2]) ? format[m2](dta[m2]) : dta[m2];  
    });  
}  

此方法就是用來填充格式數據的javascript

接下來就用示例來講明:html

例如:從服務器取出一個JSON串,把數據顯示在一組HTML控件上,如今我先把HTML代碼寫下來:java

<script type="text/template">  
<tr mgid="{mgid}" mid="{mid}">  
    <td>  
        <input type="checkbox" mid="{mid}"></td>  
    <td>  
        <a href="{localfile}" data-fancybox-group="button" class="fancybox-buttons">  
         <img src="{localfile}" style="width:45px;height:45px;"></a>  
    </td>  
    <td>  
        <input type="text" class="input-large valid" value="{medianame}" onblur="TextOnBlur(this)" onclick="TextOnFocus(this)" 
      name
="medianame" mid="{mid}" readonly="readonly"></td> <td> <a onclick="updateMediaName(this)" href="javascript:void(0);">重命名</a> <a onclick="showbulkUploadTemplate(this)" name="edit" localfile="{localfile}" href="javascript:void(0);">替換</a> <a onclick="daleteMedia(this)" href="javascript:void(0);">刪除</a> <a onclick="setMediaFaceImage(this);" title="設置爲分組【{groupname}】的封面" groupname="{groupname}" mid="{mid}" href="javascript:void(0);">設置封面</a> </td> </tr> </script>

若咱們從服務器上取到的JSON以下:ajax

{  
    "total": "1",  
    "page": "1",  
    "records": "3",  
    "rows": [{  
        "groupname": "美食圖片",  
        "mid": 4766,  
        "sid": 517,  
        "medianame": "Tulips",  
        "mgid": 549,  
        "mediatype": "image",  
        "mediaid": "",  
        "timestamp": "",  
        "localfile": "/UploadFile/image/201409/14/0x6dvf.jpg",  
        "picurl": "",  
        "thumbid": "",  
        "voiceformat": "",  
        "state": 1,  
        "createtime": "\/Date(1410673220000+0800)\/",  
        "uploadtime": "\/Date(1410673220000+0800)\/",  
        "width": 480,  
        "height": 360,  
        "seizespace": 17.41  
    }, {  
        "groupname": "美食圖片",  
        "mid": 4765,  
        "sid": 517,  
        "medianame": "Penguins",  
        "mgid": 549,  
        "mediatype": "image",  
        "mediaid": "",  
        "timestamp": "",  
        "localfile": "/UploadFile/image/201409/14/6iluw6.jpg",  
        "picurl": "",  
        "thumbid": "",  
        "voiceformat": "",  
        "state": 1,  
        "createtime": "\/Date(1410673215000+0800)\/",  
        "uploadtime": "\/Date(1410673215000+0800)\/",  
        "width": 480,  
        "height": 360,  
        "seizespace": 15.62  
    }, {  
        "groupname": "美食圖片",  
        "mid": 4764,  
        "sid": 517,  
        "medianame": "Lighthouse",  
        "mgid": 549,  
        "mediatype": "image",  
        "mediaid": "",  
        "timestamp": "",  
        "localfile": "/UploadFile/image/201409/14/fx0kzp.jpg",  
        "picurl": "",  
        "thumbid": "",  
        "voiceformat": "",  
        "state": 1,  
        "createtime": "\/Date(1410673209000+0800)\/",  
        "uploadtime": "\/Date(1410673209000+0800)\/",  
        "width": 480,  
        "height": 360,  
        "seizespace": 14.2  
    }]  
}  

填寫到定義在下面Table中json

<html>  
<body>  
<table id="tableData">  
<tr class="firstLine">  
    <th></th>  
    <th>圖片</th>  
    <th>圖片名稱</th>  
    <th>類型</th>  
    <th>大小</th>  
    <th>尺寸</th>  
    <th>上傳日期</th>  
    <th>操做</th>  
    <th></th>  
</tr>  
</table>  
</body>  
</html>  

好了準備工做作好了,重點的來了數組

$.ajax({  
    url: '/manage/GetAllMediaListPage',  
    type: 'get',  
    data: data,  
    cache: false,  
    dataType: "json",  
    success: function(dta) {  
        if (!dta || !dta.rows || dta.rows.length <= 0) {  
            return;  
        }  
  
        //獲取模板上的HTML  
        var html = $('script[type="text/template"]').html();  
        //定義一個數組,用來接收格式化合的數據  
        var arr = [];  
        //對數據進行遍歷  
        $.each(dta.rows, function(i, o) {  
            //這裏取到o就是上面rows數組中的值, formatTemplate是最開始定義的方法.  
            arr.push(formatTemplate(o, html));  
        });  
        //好了,最後把數組化成字符串,並添加到table中去。  
        $('#tableData').append(arr.join(''));  
        //走完這一步其實就完成了,不會吧,這麼簡單,不錯,就是這麼簡單!! 不信就本身動手去試試!  
    }  
});  

爲何把模板代碼放在<script></script>中間,假如,你把模板代碼放在某個<div>中並隱藏起來,那麼可能你的代碼中會用到$('input[type="text"]')查找控件時,很差意思,服務器

就會把模板中的也統計進去了,這個並非你想要的。因此我用<script>,這麼作還有一個好處,就是不會被當成HTML來執行顯示出來, 但咱們也得保證不能當成js來執行,因此app

加了個type="text/template",沒有這個類型的,本身明白就行了。curl

      另外,像o.mid的數值只會填充到{mid}這個裏,不會填充到別的地方去,並且{mid}能夠存在多個,一併所有替換成實際數值了。函數

 接下來的一個問題就是,我取到的數據可能並非我要給用戶顯示的,那麼就須要變通一下了

var html = $('script[type="text/template"]').html();  
var arr = [];  
$.each(dta.rows, function(i, o) {  
    //atime,asize和fsize這三個變量是以前的JSON中沒有的,可靈活設置一下:  
    //格式化時間,固然getFormatDate這個函數我也公佈出來了,格式化時間而已,見最後面。  
    o.atime = getFormatDate(o.uploadtime ? o.uploadtime : o.createtime, 'yyyy-MM-dd');  
    //圖片的尺寸大小: 就是把上面的o.width和o.height變量組合一下,若是任何一個不存在,則返回"-"  
    o.asize = (o.width && o.height) ? o.width + ' * ' + o.height : '-';  
    //圖片大小。存在才顯示xxKB  
    o.fsize = o.seizespace ? o.seizespace + '&nbsp; KB' : '-';  
    //格式化模板數據  
    arr.push(formatTemplate(o, html));  
});  
$('#tableData').append(arr.join(''));  

完整的HTML模板以下:

<script type="text/template">  
    <tr mgid="{mgid}" mid="{mid}">  
        <td>  
            <input type="checkbox" mid="{mid}"></td>  
        <td>  
            <a href="{localfile}" data-fancybox-group="button" class="fancybox-buttons">  
                <img src="{localfile}" style="width:45px;height:45px;"></a>  
        </td>  
        <td>  
            <input type="text" class="input-large valid" value="{medianame}" onblur="TextOnBlur(this)" onclick="TextOnFocus(this)" name="medianame" mid="{mid}"
readonly="readonly"></td> <td>{mediatype}</td> <!-- 各位看官,自定義的三個屬性在這裏哦~~ --> <td>{fsize}</td> <td>{asize}</td> <td>{atime}</td> <td> <a onclick="updateMediaName(this)" href="javascript:void(0);">重命名</a> <a onclick="showbulkUploadTemplate(this)" name="edit" localfile="{localfile}" href="javascript:void(0);">替換</a> <a onclick="daleteMedia(this)" href="javascript:void(0);">刪除</a> <a onclick="setMediaFaceImage(this);" title="設置爲分組【{groupname}】的封面" groupname="{groupname}" mid="{mid}" href="javascript:void(0);">設置封面</a> </td> </tr> </script>

附: 格式化時間函數:

function getFormatDate(xdate, format) {  
    try {  
        var format = format || 'yyyy-MM-dd HH:mm:ss';  
        var date = (xdate instanceof Date) ? xdate : new Date(parseInt(xdate.replace('/Date(', '').replace(')/', ''), 10));  
        var lang = {  
            'M+': date.getMonth() + 1,  
            'd+': date.getDate(),  
            'H+': date.getHours(),  
            'm+': date.getMinutes(),  
            's+': date.getSeconds()  
        };  
        if (/(y+)/.test(format)) {  
            format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));  
        }  
        for (var key in lang) {  
            if (new RegExp('(' + key + ')').test(format)) {  
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?  
                    lang[key] : ('00' + lang[key]).substr(('' + lang[key]).length));  
            }  
        }  
        return format;  
    } catch (e) {  
        return '-';  
    }  
}  
相關文章
相關標籤/搜索