• 【LayUi】动态数据表格+分页+CheckBox


    功能描述:

    使用layui动态生成带有复选框的table,初始化打开时回显复选框选中项;翻页时记录勾选的数据;

    效果展示:

    aspx部分代码:

    <div id="divResourcePackList">
        <p style="margin-bottom: 5px">共计资源包<span id="packCount" style="color: blue">0</span>个,已选<span id="checkedCount" style="color: red">0</span></p>
        <table id="tbResourcePack" lay-filter="tbResourcePack"></table>
    </div>

    JS部分代码:

    <script>
        var data_view = new Vue({
            el: '#data_view',
            data: {
                brandList: [],   //品牌信息 
                storeList: [],  //品牌门店信息 
                CheckedArray: [], //记录选中行ID
                brandIndex: '1',
                pageSize: '10',
                brandIDs: '',
                form: '',
            }, 
            mounted: function () {
                var that = this;
                layui.use(['form', 'upload', 'laypage', 'table'], function () {
                    form = layui.form; 
    
                    form.render(); 
                })
            },
            methods: {  
                //加入资源包按钮点击事件
                addStoreToResourcePack: function () {
                    var storeIds = "";
                    var that = this;
                    var brandID = $('#txtBrandId').val();
                    var param = {
                        brandID: brandID,
                        flag: 'GetCakeStoreID'
                    }
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        url: '../handle/Store.ashx',
                        data: param,
                        async: false,
                        success: function (data) {
                            //console.log(data) 
    
                            var storeIdList = data.data;
                            if (storeIdList.length > 0) {
                                var strStoreIds = "";
                                for (var i = 0; i < storeIdList.length; i++) {
                                    strStoreIds += storeIdList[i].ID + ",";
                                }
                                storeIds = strStoreIds.substring(0, strStoreIds.length - 1);
    
                                //打开弹出框,生成table
                                that.OpenResourcePage(storeIds, brandID);
                            }
                        }
                    });
                },
    
                OpenResourcePage: function (storeIds, storeBrandID) {
                    var that = this;
                    var params = {
                        flag: 'GetResourcePackList'
                    }
                    var layTable = layui.table;
                    var dataArr = [];//当前页面数据  
                    //打开弹出框页面
                    layer.open({
                        type: 1,
                        title: ['加入资源包', 'font-size:16px;'],
                        area: ['900px'],
                        btn: ['确定', '取消'],
                        content: $('#divResourcePackList'),
                        success: function (layero, index) {
                            //加载layui-table实例
                            layTable.render({
                                id: 'tbResourcePack',
                                elem: '#tbResourcePack', //指定原始表格元素选择器(推荐id选择器) 
                                page: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                                limit: 10,
    
                                cols: [[ //标题栏,设置表头 
                                    { checkbox: true, title: '全选' }
                                    , { field: 'ID',  80, title: 'ID' }
                                    , { field: 'ResourcePackNo',  120, title: '资源包编号' }
                                    , { field: 'Name',  150, title: '资源包名称' }
                                    , { field: 'Describe', title: '备注说明' }
                                ]],
                                method: 'post',
                                url: '../handle/Store.ashx',
                                contentType: 'application/x-www-form-urlencoded',
                                where: params,
                                request: {
                                    pageName: 'pageIndex', //页码的参数名称,默认:page
                                    limitName: 'pageSize' //每页数据量的参数名,默认:limit
                                },
                                parseData: function (res) {
                                    //console.log(res)  
                                    dataArr = res.data
                                    return {
                                        "code": '0', //解析接口状态
                                        "msg": res.message, //解析提示文本
                                        "count": res.result, //解析数据长度
                                        "data": res.data //解析数据列表
                                    };
                                },
                                done: function (res) {
                                    //console.log(res)
                                    //console.log(that.CheckedArray)
                                    document.getElementById('packCount').innerHTML = res.count; //资源包总数  
                                    document.getElementById('checkedCount').innerHTML = that.CheckedArray.length; //选中数量(回显)    
    
                                    var data = res.data;    //资源包列表数据
                                    var num = 0;
                                    for (var i = 0; i < data.length; i++) {
                                        for (var j = 0; j < that.CheckedArray.length; j++) {
                                            if (data[i].ResourcePackNo == that.CheckedArray[j]) {
                                                num++;
                                                data[i]["LAY_CHECKED"] = 'true';    //真正的有效勾选,只有改变LAY_CHECKED的值, table.checkStatus才能抓取到选中的状态
                                                var index = data[i]['LAY_TABLE_INDEX'];
                                                $('#divResourcePackList tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                                $('#divResourcePackList tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                                            }
                                        }
                                    }
                                    var limits = $(".layui-laypage-limits").find("option:selected").val(); //每页条数的选择项,值务必对应 limit 参数
                                    //"全选"框被勾选
                                    if ((num == limits || num == res.count) && res.count > 0) {
                                        $('#divResourcePackList .layui-table-header table.layui-table thead th input[type="checkbox"]').prop('checked', true);
                                        $('#divResourcePackList .layui-table-header table.layui-table thead th input[type="checkbox"]').next().addClass('layui-form-checked');
                                    }
                                }
                            });
    
                            //复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
                            layTable.on('checkbox(tbResourcePack)', function (obj) {
                                if (obj.checked == true) {
                                    if (obj.type == 'one') {
                                        that.CheckedArray.push(obj.data.ResourcePackNo);
                                    } else {
                                        for (var i = 0; i < dataArr.length; i++) {
                                            that.CheckedArray.push(dataArr[i].ResourcePackNo);
                                        }
                                        //去重
                                        var array = [];
                                        for (var i = 0; i < that.CheckedArray.length; i++) {
                                            if (array.indexOf(that.CheckedArray[i]) === -1) {
                                                array.push(that.CheckedArray[i])
                                            }
                                        }
                                        that.CheckedArray = array;
                                    }
                                } else {
                                    if (obj.type == 'one') {
                                        for (var i = 0; i < that.CheckedArray.length; i++) {
                                            if (that.CheckedArray[i] == obj.data.ResourcePackNo) {
                                                that.removeByValue(that.CheckedArray, that.CheckedArray[i]);//调用自定义的根据值移除函数
                                            }
                                        }
                                    } else {
                                        for (var i = that.CheckedArray.length - 1; i > -1; i--) {   //splice删除后会更改原数组下标所代表的值
                                            for (var j = dataArr.length - 1; j > -1; j--) {
                                                if (that.CheckedArray[i] == dataArr[j].ResourcePackNo) {
                                                    that.removeByValue(that.CheckedArray, that.CheckedArray[i]);//调用自定义的根据值移除函数 
                                                }
                                            }
                                        }
                                    }
                                }
    
                                document.getElementById('checkedCount').innerHTML = that.CheckedArray.length; //选中数量   
                                //console.log(that.CheckedArray)
                            });
                        },
                        yes: function (index, layero) { //点击弹出框的"确定"按钮
                            //var checkStatus = layTable.checkStatus('tbResourcePack');
                            var storeParams = {
                                storeBrandID: storeBrandID,
                                storeIds: storeIds,
                                //checkData: JSON.stringify(checkStatus.data),    //选中行数据
                                checkedResourceNo: JSON.stringify(that.CheckedArray),    //选中行数据:ResourceNo
                                loginer: '<%= Session["operName"]%>',
                                flag: 'AddStoreToResourcePack'
                            }
    
                            $.ajax({
                                type: "post",
                                dataType: "json",
                                url: '../handle/Store.ashx',
                                data: storeParams,
                                async: false,
                                cache: false,
                                success: function (data) {
                                    //console.log(data)   
                                    if (data.result == "0") {
                                        layer.alert('操作成功', {
                                            icon: 1,
                                            title: '提示',
                                            closeBtn: 0,
                                            yes: function () {
                                                window.location.reload();
                                            }
                                        });
                                    } else {
                                        layer.alert('操作失败', {
                                            icon: 2,
                                            title: '提示',
                                            closeBtn: 0
                                        });
                                    }
                                }
                            });
                        }
                    });
                },
    
                //自定义方法,根据值去移除 
                removeByValue: function (arr, val) {
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i] == val) {
                            arr.splice(i, 1);
                            break;
                        }
                    }
                },
            }
        })
    </script>
    View Code

    保存复选框勾选数据时,添加新勾选的数据,删除取消勾选的数据

    public static bool UpdateHotProducts(string ModularType, List<string> newGoodsId)
    {
        try
        {
            List<string> sqlList = new List<string>();
            DataTable tableGoods = GetHotProductList(ModularType, "", "", 0, 0); //原热门推荐商品列表
            List<string> goodsId = new List<string>();
            string flName = GetFloorName(ModularType);
    
            if (tableGoods != null && tableGoods.Rows.Count > 0)
            {
                foreach (DataRow item in tableGoods.Rows)
                {
                    goodsId.Add(item["GoodsID"].ToString()); //添加原商品id
                }
            }
    
            foreach (var newItem in newGoodsId)
            {
                //保存的勾选中的热门推荐商品中有,原热门推荐商品列表没有就新增
                if (!goodsId.Contains(newItem))
                {
                    sqlList.Add(string.Format(@" insert into dbo.GoodProduct ( GoodsId, CreateTime, DeleteStatus, Sort, ModularType, ModularName )  
                                        values ('{0}', getdate(), 0, 0, '{1}', '{2}') ", newItem, ModularType, flName));
                }
            }
            foreach (var item in goodsId)
            {
                //原热门推荐商品有,保存的勾选中的热门推荐商品没有就删除
                if (!newGoodsId.Contains(item))
                {
                    //删除取消勾选的热门推荐商品
                    sqlList.Add(string.Format(@"  delete dbo.GoodProduct where GoodsID='{0}' and ModularType='{1}' ", item, ModularType));
                }
            }
    
            Ruby_DAL.DbHelperSQL.ExecuteSqlTran(sqlList);
            return true;
        }
        catch (Exception ex)
        {
            Ruby_Common.LogRecord.WriteLog.WriteLog_Info("Info", new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().ReflectedType.Name, new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name, "设置热门推荐商品出现错误,错误信息:" + ex.Message);
            return false;
        }
    }
    View Code

     

     

     

  • 相关阅读:
    2020 CCPC-Wannafly Winter Camp Day6 ---I. 变大!
    Codeforces 1295F Good Contest
    2020 CCPC-Wannafly Winter Camp Day6 ---A. Convolution
    centos下kubernetes+flannel部署(旧)
    无网络centos7中部署kubernetes
    利用Openvswitch实现不同物理机中的Docker容器互连
    docker-py的配置与使用
    通过Docker配置DNS服务器
    在 OS X Yosemite 中部署Mesos
    Docker初识
  • 原文地址:https://www.cnblogs.com/zhaoyl9/p/14517022.html
Copyright © 2020-2023  润新知