zoukankan      html  css  js  c++  java
  • 实现layui table筛选框记忆功能

     碰到表中列很多如下表

     

    使用layui table的筛选功能.选完之后呢,关掉浏览器再打开或者换个页面再打开的时候,选择就白选了.这种情况下,客户就要求加个记忆功能.让她下次再打开的时候,还能记忆上次选择的

    网上几乎没有这种使用的例子.总之是没有找到相关资料,于是我就把实现的过程记录下来,方便大家用到的时候做个参考.

    实现: 记忆的数据可以存到数据库,可以存到本地缓存

    本案例放入本地缓存的方式

    使用 MutationObserver  实现监控点击事件.

    由于筛选的跳窗是点开后后加的代码,所以一般的事件onclick是触发不到的.. 就是点击筛选按钮,此时加载跳出框代码, 也就在此是注册onclik 点击事件是不行的. 如果早注册事件,早于页面元素注册,也是抓不到事件滴.页面还没渲染出来,早早的注册了页面里边的点击事件,后来页面渲染出来后,点击是无法响应的,有个先后顺序.

    经过控制台点击按钮分析页面代码等等操作

    /////筛选框记忆功能
    //1页面打开,先读本地缓存
    //2读入cols 设置hide true 或者false
    //3渲染table
    //4加入 筛选框选择框事件获取 并设置本地缓存
    <script src="JQuery/jquery-2.2.2.min.js"></script>
    <script src="/layui-v2.6.4/layui.js"></script>
    <script>
        layui.use(['table','form'], function(){
            var table = layui.table;
            var $ = layui.$;//等同于jquery
            var form = layui.form;
            //选择
            form.on('select(TableName)', function(data){
                $.ajax({
                    type: 'get',
                    url: '/sss',
                    data: {OptionTableID:data.value},
                    async:false,
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);
                        var strHtml = "<option value=''>请选择</option>";
                        for (var i = 0; i < data.length; i++) {
                            strHtml += "<option value='"+data[i].OptionColumnID+"'>"+data[i].ColumnDisplayName+"</option>";
                        }
                        $("#OptionColumnID").html(strHtml);
                        form.render('select');
                    },
                    error:function(e){
                    }
                });
            });
         /*   window.localStorage.setItem('UserName',$("#UserName").val());
            window.localStorage.setItem('Password',$("#Password").val());*/
    
            /////筛选框记忆功能
            //1页面打开,先读本地缓存
            //2读入cols  设置hide true 或者false
            //3渲染table
            //4加入 筛选框选择框事件获取 并设置本地缓存
            var cols=[[
                {checkbox: true, field:'OptionColumnValueID'},
                {field: "OptionColumnValueID", hide:false, title: "ID", sort: true},
                {field: "ColumnValue", hide:false, title: "字典名称"}   ,      
                {title: "操作",  align: "center", fixed: "right", templet: "#barDemo"}
            ]];
            intCols();
           function  intCols()
           {
               for (var i=0;i<cols[0].length;i++)
               {
                   if(cols[0][i].field!=undefined)
                   {
                       let localfield='test'+cols[0][i].field;
                       let hidevalue =window.localStorage.getItem(localfield);
                       if(hidevalue==='false')
                       {
                           cols[0][i].hide=false;
                       }else if(hidevalue==='true')
                       {
                           cols[0][i].hide=true;
                       }
                   }
               }
           }
            //方法级渲染
            table.render({
                elem: '#LAY_table_user'//table元素的ID
                ,id: 'test'//容器的ID
                //,toolbar: "#toolbarTpl"
                ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
                ,defaultToolbar: ['filter', 'exports', 'print']
                ,url: '/ist'
                ,cols: cols
                /*  ,done: function () {
                      $("[data-field='OptionColumnValueID']").css('display','none');
                  }*/
                ,page: true
                ,limits: [10,1000,10000]
                ,limit: 10
                ,where: {
                }
            });
    
    
            /////筛选框记忆功能
            //1页面打开,先读本地缓存
            //2读入cols  设置hide true 或者false
            //3渲染table
            //4加入 筛选框选择框事件获取 并设置本地缓存
    
    
            // 选择需要观察变动的节点
            const targetNode =document.getElementsByClassName('layui-table-tool');//document.getElementById('some-
            const targetNode1 =document.getElementsByClassName('layui-table-tool-self')[0];//document.getElementById('some-id');
          //  console.log(targetNode);
          //  console.log(targetNode1);
    // 观察器的配置(需要观察什么变动)
            const config = { attributes: true, childList: true, subtree: true };
    
    // 当观察到变动时执行的回调函数
            const callback = function(mutationsList, observer) {
                console.log(mutationsList);
              //  console.log(observer);
                // Use traditional 'for loops' for IE 11
                for(let mutation of mutationsList) {
                    if (mutation.type === 'childList') {
                       // console.log('A child node has been added or removed');
                    }
                    else if (mutation.type === 'attributes') {
                        console.log(mutation.target.innerText);
                        //先根据innertext 列名称 对cols 进行field 查询,查到field 可以找到本地缓存的字段,约定,本地缓存的命名规则为表名字母缩写_加field名组成,防止冲突
                        var field="";
                        for (var i=0;i<cols[0].length;i++)
                        {
                            if(cols[0][i].title===mutation.target.innerText)  //标题相同 则取field
                            {
                                field=cols[0][i].field;
                                break;
                            }
                        }
                         if(field!=="")
                         {
                            // 组装缓存key
                             let localkey='test'+field;
                             //判断value值
                            if(mutation.target.classList[2]!=undefined) //说明2: "layui-form-checked"  复选框是已选择的,说明此列是在表中显示的
                            {
                                window.localStorage.setItem(localkey,false);
                            }else  //没被选择,说明此列不在table中显示
                            {
                                window.localStorage.setItem(localkey,true);
                            }
                         }
                    }
                }
            };
    
    // 创建一个观察器实例并传入回调函数
               const observer = new MutationObserver(callback);
    
    // 以上述配置开始观察目标节点
               observer.observe(targetNode1, config);
    
            //监听工具条
            table.on('toolbar()', function(obj){
                var data = obj.data;
                console.log(obj);
    
            });
    
    
    
    
            //监听工具条
            table.on('tool(user)', function(obj){
                var data = obj.data;
                console.log(obj);
                if(obj.event === 'del'){
                    layer.confirm('确定要删除:'+data.ColumnValue+'么?',
                        {
                            title: '删除',
                            btn: ['确定', '取消']
                        },function(index){
                            autid(data.OptionColumnValueID,table);
                            //obj.del();
                            layer.close(index);
                        });
                }else if(obj.event === 'edit'){
                    window.location.href="/xxx/xxxx
                }
                else if(obj.event === 'LAYTABLE_COLS'){
                    console.log(123) ;           }
            });
            //监听工具条结束
    
            //监听排序
            table.on('sort(user)', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
                table.reload('test', {//刷新列表
                    initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。 layui 2.1.1 新增参数
                    ,where: { //请求参数
                        field: obj.field //排序字段
                        ,order: obj.type //排序方式
                    }
                });
            });
            //监听排序结束
    
            //查询
            $("#chaxun").click(function(){
                table.reload('test', {//刷新列表
                    where: {
                        OptionTableID:$('#TableName').val()
                        ,OptionColumnID:$('#xxx').val()
                    },page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            })
    
            //批量
            $("#allDel").click(function(){
                var checkStatus = table.checkStatus('test')
                    ,data = checkStatus.data;
                if (data === undefined || data.length == 0) {
                    layer.alert("请勾选要操作的数据!")
                }else{
                    var itemids='';
                    for(var o in data){
                        itemids +=data[o].xxx+",";
                    }
                    layer.confirm('确定要删除选中的数据吗?',
                        {
                            title: '删除',
                            btn: ['确定', '取消']
                        },function(index){
                            autid(itemids,table);
                            //obj.del();
                            layer.close(index);
                        });
                }
            });
        });
        function autid(itemids,table){
            var indexload = layer.load(1, {
                shade: [0.3,'#000'],
                success: function(layero, indexload){
                    $.ajax({
                        url: '/xxx',
                        type:'POST',
                        dataType: 'json',
                        data: {
                            itemIds:itemids
                        },
                        success: function (ret) {
                            console.log(ret)
                            if(ret.res=="ok"){
                                layer.alert('操作成功!', function(index){
                                    layer.close(index);
                                    layer.close(indexload);
                                    table.reload('test', {
                                        where: {
                                        }
                                    });
                                });
                            }else{
                                layer.close(indexload);
                            }
                        }
                    });
                }
            });
        }
    </script>
    技术交流qq群:143280841
  • 相关阅读:
    DP大作战—状态压缩dp
    DP大作战—组合背包
    DP大作战——多重背包
    单链表的使用——计算多项式加法
    单链表逆置
    钢条切割问题
    哈夫曼树及解码
    双“11”的抉择
    矩阵链相乘助教版代码
    abs()函数的返回值问题
  • 原文地址:https://www.cnblogs.com/zuochanzi/p/14721567.html
Copyright © 2011-2022 走看看