實現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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM