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

Json-display

时间:2015-07-16 18:39:50      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

(function(factory) {
    if (typeof define === ‘function‘ && define.amd) {
        // AMD
        define([‘jquery‘], factory);
    } else if (typeof module === ‘object‘ && module.exports) {
        factory(require(‘jquery‘));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($, undefined) {

    $.fn.ajaxdisplay = function (data, options) {
        var tpl,count = 0, $tag,$this = this,dataobj;
        var defaults = {
            template: $this.html(),
            oddClass: ‘‘,
            evenClass: ‘‘,
        };
        try {
            if (typeof data == "object") {
                dataobj = data;
            } else {
                dataobj = eval(‘(‘ + data + ‘)‘);
            }
        } catch (err) {
            console.log(err);
            return $this;
        }
        settings = $.extend({}, defaults, options);
        tpl = settings.template;
        $this.html(‘‘);
        for (var x in dataobj) {
            $tag = $(TplReplace(tpl, dataobj[x]));
            $tag.addClass(count % 2 == 0 ? settings.evenClass : settings.evenClass);
            $this.append($tag);
            count++;
        }
    }
       

    function TplReplace(tpl,obj) {
        if(tpl.trim()!=‘‘){
            return tpl.replace(/\{([\w\.]*)\}/g,function(str,key){
                var keys = key.split(‘.‘),v = obj[keys.shift()];
                for(var x in keys){
                    v = v[keys[x]];
                }
                return (typeof v !== "undefined" && v !== null) ? v : "";
            });
        } else {
            var tagstr = ‘<tr>‘;
            for (var x in obj) {
                tagstr += ‘<td>‘ + obj[x] + ‘</td>‘;
            }
            tagstr += ‘</tr>‘;
            return tagstr;
        }       
    }
}));

 

Json-display

标签:

原文地址:http://www.cnblogs.com/luowenxing/p/4651685.html

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