博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jquery动态绑定像Repeater和dataList一样绑定数据源
阅读量:5111 次
发布时间:2019-06-13

本文共 6249 字,大约阅读时间需要 20 分钟。

//将json数据绑定到具有模板的Table中

$.fn.dataBind = function (options) {
    var target = this;
    var defaults = {

        expand: false,

        loading: true,
        showPager: true,
        cache: true,
        cacheName: undefined,
        emptyMessage: '<div class="text_empty">没有数据内容。</div>',

        data: undefined,

        template: undefined,

        url: undefined,

        keyValue: '',
        pageSize: 10,
        currentPage: 1,

        modelLine: 1,

        modelType: undefined,

        onDataBindSuccess: undefined,

        onLoadSuccess: undefined,
        onItemBind: undefined,
        onError: undefined
    };

    var settings = settings || $.extend({}, defaults, options);

    if (settings.cache == true) {
        settings.cacheName = settings.cacheName || ('d_' + (settings.url || '') + settings.currentPage + settings.keyValue).replace('-', '_');
        try {
            settings.data = settings.data || ($.parseJSON($(target).data(settings.cacheName)));
        }
        catch (e) { }
    }

    if (!settings.modelType) {

        if ($(target).is('ul')) {
            settings.modelType = 'li';
        }
        else if ($(target).is('table')) {
            settings.modelType = 'tbody>tr';
        }
    }
    var template = settings.template || $(target).find(settings.modelType + ':lt(' + settings.modelLine + ')').hide().clone().show().outer();
    var loadingFrame;
    if (settings.loading) {
        $('#loadingForm').popFrameClose();
        loadingFrame = $('<div id="loadingForm" class="text_center img_v_middle" style="line-height:15px;"><img src="数据加载中...." alt=""/> </div>')
            .appendTo(document.body).popFrame({ trigger: target, position: 'center', removeTargetOnClose: true, toolBox: false, height: 20, width: 30 });
    }

    if (settings.data) {

        bindJson(settings);
        if (loadingFrame) {
            $(loadingFrame).popFrameClose();
        }
    }
    else if (settings.url) {
        $.ajax({
            type: 'POST',
            data: { KeyValue: (settings.keyValue + "," + settings.currentPage + "," + settings.pageSize) },
            url: settings.url,
            success: function (result) {
                result = $(result).find("string").text();
                var json;
                try {
                    json = $.parseJSON(result);
                }
                catch (e) {
                    $.debug('返回的内容无法格式化成JSon', true);
                    if (settings.onError) {
                        settings.onError(e);
                    }
                    return;
                }
                if (settings.cache == true) {
                    $(target).data(('d_' + (settings.url || '') + settings.currentPage + settings.keyValue).replace('-', '_'), result);
                }
                settings.data = json;
                bindJson(settings, result);
                if (loadingFrame) { $(loadingFrame).popFrameClose(); }
            },
            error: function (errMessage) {
                if (loadingFrame) { $(loadingFrame).popFrameClose(); }
                if (settings.onError) {
                    settings.onError(errMessage);
                }
                else {
                    $('<div id="loadingForm" class="text_center img_v_middle text_important" style="line-height:15px;">意外错误<p>' + errMessage.responseText + '</p></div>').appendTo(document.body).popFrame({ trigger: target, position: 'center', removeTargetOnClose: true, toolBox: false, height: 20, width: 80, autoClose: 3000 });
                }
            }
        });
    }
    else {
        $(loadingFrame).popFrameClose();
    }
    function bindJson(settings, result) {
        if (settings.onLoadSuccess) {
            settings.onLoadSuccess(result, settings.data, settings);
        }
        if (settings.data) {
            var templateHtml = template.replace(/[\r\n]/g, '');

            var columns = new Array();

            var regKey = new RegExp(/@-.*?-@/g);
            while ((result = regKey.exec(templateHtml)) != null) {
                columns.push(result[0]);
            }
            var pattern = '/(.*)' + columns.join('(.*)') + '(.*)/g';
            var reg = new RegExp(eval(pattern));
            //---------------------------------------------//
            var stringbulder = '';
            var table = settings.data.Table || settings.data;
            $.each(table, function (i, item) {
                if (settings.onItemBind) {
                    var bindResult = settings.onItemBind(item);
                    if (!bindResult) {
                        return true;
                    }
                }
                var replaceValue = '';
                $.each(columns, function (j) {
                    var itemStr = eval('item.' + columns[j].substring(2, columns[j].length - 2)) || '';
                    if (columns.length >= 10) {
                        if (!isNaN(itemStr)) {
                            itemStr = ' ' + itemStr;
                        }
                    }
                    replaceValue += ('$' + new Number(j + 1) + itemStr);
                });
                replaceValue += ('$' + (columns.length + 1));
                stringbulder += templateHtml.replace(reg, replaceValue);
            });
            if (settings.expand) {
                $(target).find(settings.modelType + ':last').after(stringbulder);
            }
            else {
                var length = $(target).find(settings.modelType).length;
                if (length > 0) {
                    $(target).find(settings.modelType + ':gt(' + (settings.modelLine - 1) + ')').remove();
                    $(target).find(settings.modelType + ':last').after(stringbulder);
                }
                else {
                    $(target).append($(stringbulder));
                }
            }
            //------------------------------------------------//
            var footer = $(target).find('tfoot>tr>td');
            if (settings.showPager && footer.length > 0 && settings.data.Pager && settings.data.Pager[0].PageCount > 1) {
                var pagerString = '';
                for (var i = 1; i <= settings.data.Pager[0].PageCount; i++) {
                    if (settings.currentPage == i) {
                        pagerString += ('[' + i.toString() + ']&nbsp;');
                    }
                    else {
                        pagerString += ('[<a href="javascript:void(0)">' + i.toString() + '</a>]&nbsp;');
                    }
                }
                $(target).find('tfoot>tr>td').html('<div class="text_center box_padding">' + pagerString + '</div>');

                $(target).find('tfoot>tr>td>div>a').bind('click', function () {

                    settings.currentPage = parseInt($(this).text());
                    var pagerSetting = $.extend({}, defaults, settings);
                    pagerSetting.data = undefined;
                    $(target).dataBind(pagerSetting);
                });
            }

            var dataCount = $(target).find(settings.modelType + '').length; //获得Tbody中存在数据的值

            if (dataCount == settings.modelLine) {
                $(target).find('tfoot>tr>td').html(settings.emptyMessage);
            }
            //            else {
            //                $(target).find('tfoot>tr>td').html('');
            //            }
            //            $(template).hide();
            if (settings.onDataBindSuccess) {
                settings.onDataBindSuccess(result, settings.data, settings);
            }
        }
    }
    return target;
}

在这里必须table的模版必须使用如下格式:<table id="tbCompanyUserList" class="frame">

                            <thead>
                                <tr>
                                    <th style="width: 0.5em;">
                                    </th>
                                    <th scope="col" style="width: 80px;">
                                        姓名
                                    </th>
                                    <th scope="col" style="width: 160px;">
                                        职位
                                    </th>
                                    <th>
                                        公司名称
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                    </td>
                                    <td>
                                        <a role="popUserInfo" class="logo_user_small" userid="@-UserId-@">@-RealName-@</a>
                                    </td>
                                    <td>
                                        @-Title-@
                                    </td>
                                    <td>
                                        @-CompanyName-@
                                    </td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="4" class="text_center">
                                    </td>
                                </tr>
                            </tfoot>
                        </table>

不好意思忘了写用法了如下: $('#tbCompanyUserList).dataBind({

            url: cfsns.url.company.newsList,
            keyValue: companyId,
            modelLine: 1,
            emptyMessage: '<div class=\"text_unimportant text_center\">!</div>',
            onLoadSuccess: function (jsonstr, json) {
                                       });
                    }
                }
            },
            onDataBindSuccess: function (result, json, setting) {
                                }
            }
        });
    }

支持div和table的绑定,如果有错请联系我,我会尽快改正!

转载于:https://www.cnblogs.com/Minghao_HU/archive/2012/08/13/2636187.html

你可能感兴趣的文章
Master选举原理
查看>>
[ JAVA编程 ] double类型计算精度丢失问题及解决方法
查看>>
小别离
查看>>
微信小程序-发起 HTTPS 请求
查看>>
WPF动画设置1(转)
查看>>
基于node/mongo的App Docker化测试环境搭建
查看>>
秒杀9种排序算法(JavaScript版)
查看>>
struts.convention.classes.reload配置为true,tomcat启动报错
查看>>
MySQL的并行复制多线程复制MTS(Multi-Threaded Slaves)
查看>>
好玩的-记最近玩的几个经典ipad ios游戏
查看>>
PyQt5--EventSender
查看>>
Sql Server 中由数字转换为指定长度的字符串
查看>>
Java 多态 虚方法
查看>>
Unity之fragment shader中如何获得视口空间中的坐标
查看>>
万能的SQLHelper帮助类
查看>>
tmux的简单快捷键
查看>>
[Swift]LeetCode922.按奇偶排序数组 II | Sort Array By Parity II
查看>>
Html5 离线页面缓存
查看>>
《绿色·精简·性感·迷你版》易语言,小到不可想象
查看>>
Android打包key密码丢失找回
查看>>