Layui前端框架


官網

https://www.layui.com/

datagrid

復選框不居中顯示問題

.layui-table-cell .layui-form-checkbox[lay-skin="primary"]{
     top: 50%;
     transform: translateY(-50%);
}

獲取所選行指定屬性

獲取datagrid復選框選定行的指定屬性,返回以逗號分割的字符串屬性。后台可以直接用list或者String[]接收數據.

        /**
         * 獲取所選行ids
         * tableidStr dagagridtable的id,例如'dataGridList'
         * idObj 屬性,例如'sysid'
         **/
        function getAllCheck(tableidStr,idObj){
            var ids_arr = [];
            var checkStatus = table.checkStatus(tableidStr);
            var rows = checkStatus.data;
            for(var i in rows){
                ids_arr.push(rows[i][idObj]);  //獲取row[i]數據行的idObj屬性
            }
            var ids_result = ids_arr.join(',');
            return ids_result;
        }

分頁&條件查詢

先分頁查詢,翻頁后再輸入條件進行查詢,此時查詢條件會把當前頁數給帶過去,一定要把page的當前頁置為1

            table.reload('dataGridList', {
                url: "./authrole/getListByPage",
                page:{
                    curr:1
                }
                ,where: {rolename:rolename} 
            });

form表單

驗證取消必填

需要修改兩個文件:form.js和layui.all.js

phone:[/(^$)|^1\d{10}$/,'請輸入正確的手機號'],
email:[/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,'郵箱格式不正確'],
url:[/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/,'鏈接格式不正確'],
number:[/(^$)|^\d+$/,'只能填寫數字'],
date:[/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,'日期格式不正確'],
identity:[/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/,'請輸入正確的身份證號']

新增部分:(^$)|

如果該選項為必填:建議使用,lay-verify=“required|number”校驗

button點擊頁面刷新

button在form表單中,點擊button會導致頁面刷新,需要加上type="button"

<button class="layui-btn ty-btn" type="button" onclick="active()">激活</button>

下拉框動態數據

html

<select name="type" id="type_up" lay-verify="" lay-verify="">
     <option value="">請選擇</option>
</select>

js

    layui.use('form', function(){
        var form = layui.form;
        $.ax('./setting/selectByExample', {type:'warnconfig_type'}, 'POST', function(data) {
            /*success*/
            var selects='';
            /*遍歷數據,生成option選項*/
            for(var i in data){
                var  its='<option value="'+data[i].code+'">'+data[i].value+'</option>';
                selects +=its;
            }
            /*添加到指定的下拉框下面*/
            $("#type_up").append(selects);
            /*渲染*/
            form.render('select')
        }, function(e) {
            /*error*/
        }, false); //同步
    });

下拉框回顯

/*遍歷id為type_up的下拉框,因為只有一個所以只執行一次*/
$("#type_up").each(function() {
  /*遍歷下拉框下的option子結點*/
    $(this).children("option").each(function() {
      //移除option的selected屬性
        $(this).removeAttr("selected");
        //如果option的value和回顯數據的type值相同
        if (this.value == d.type) {
            //選中下拉框中的值
        $('#type_up').val(d.type);
        }
    });
});

/*渲染下拉框*/
layui.use('form', function(){
    var form = layui.form;
  form.render('select');
});

下拉框清空

        function queryClear(){
            layui.use('form', function(){
                $('#isActiveQuery').val('');  //先設置值
                var form = layui.form;    
                form.render('select'); //刷新select選擇框渲染
            });
        }

Radio渲染不上去

                <div class="layui-input-block">
                    <input type="radio" name="sex_up" value="1" title="男" checked>
                    <input type="radio" name="sex_up" value="0" title="女">
                </div>

                layui.use('form', function(){
                    if(d.sex == 0){
                        $("input[name=sex_up][value='0']").prop("checked", d.sex == 0 ? true : false);
                    }else{
                        $("input[name=sex_up][value='1']").prop("checked", d.sex == 1 ? true : false);
                    }
                    var form = layui.form;
                    form.render("radio"); //更新全部
                });

CheckBox布局混亂

Checkbox框高度過高

.layui-form-checkbox[lay-skin=primary],.layui-form-checkbox[lay-skin=primary] span{
     max-height: 20px;
}

Checkbox監控選擇框

在選擇第六個時彈出來最多只能選擇五個

html

<input name="roleids[]" lay-filter="checkbox_role-filter" lay-skin="primary" type="checkbox" value="admin1" title="管理員">

js

          /*lay-filter='checkbox_role-filter'的復選框*/
          form.on('checkbox(checkbox_role-filter)',function(data){
            console.log(data);
            if ($("input[lay-filter='checkbox_role-filter']:checked").length>5){
                //將選中的全部取消
                //$("input[lay-filter='checkbox_role-filter']:checked").removeAttr("checked");
                //$(this).checked = false;
                $(this).prop("checked", false); 
                form.render('checkbox'); 
                layer.msg("最多只能選擇5個標簽", {
                    time : 3000,
                    icon : 10 
                });
            }
          });

Checkbox獲取值

            //獲取checkbox[lay-filter='checkbox_role-filter']的值,ssm可以直接用String[]接收
            var arr = new Array();
            $("input[lay-filter='checkbox_role-filter']:checked").each(function(i){
                arr[i] = $(this).val();
            });
            var roleids = arr.join(',');

動態添加Checkbox

            //所有角色復選框
            $.ajax({
                url: "./authrole/selectByExample"
                    , data: {}
                    , type: "post"
                    , dataType: "json"
                    , success: function (data) {
                        var str = '';
                        $.each(data, function (index, role) {
                            str +='<input name="roleids[]" lay-filter="checkbox_role-filter" lay-skin="primary" type="checkbox" value="'+role.id+'" title="'+role.rolename+'">';
                        });
                        //放入html中
                        $('#rolesCheckboxDiv').html(str);
                        //渲染表單
                        layui.use('form', function(){
                            var form = layui.form;
                            form.render("checkbox"); //渲染checkbox
                        });
                    }
                    ,error:function(e){
                        layer.alert("請求失敗",{title:'提示',icon: 2});
                    }
            });

switch控件

datagrid中switch控件

    //動態添加switch
    templet: function(d){
         if(d.isActive == 0)
               return '<input type="checkbox" value="'+d.groupid+'" lay-text="啟用|停用" lay-filter="switchFilter" name="switch" lay-skin="switch">';
         if(d.isActive == 1)
            return '<input type="checkbox" value="'+d.groupid+'" checked="" lay-text="啟用|停用" lay-filter="switchFilter" name="switch" lay-skin="switch">';
    }

        //switch事件監控
        layui.use(['form'], function(){
            var form = layui.form
                ,layer = layui.layer
            //監聽switchFilter開關
            form.on('switch(switchFilter)', function(data){  //data為switch控件,用控件的value屬性傳值;
                var groupid = data.value;
                var isActive = '';
                console.info();
                if(this.checked){
                    isActive = '1';
                    //layer.msg('開關checked:'+ (this.checked ? 'true' : 'false'), {offset: '6px'});
                    //layer.tips('溫馨提示:開關狀態的文字可以隨意定義,而不僅僅是ON|OFF', data.othis)
                }else{
                    isActive = '0';
                    //layer.msg('開關: 關掉了', {offset: '6px'});
                }

                //do some ajax opeartiopns;
                $.ax('./group/switchAcitve', {groupid:groupid,isActive:isActive}, 'POST', function(data) {
                    if (data.code == "success") {
                        layer.msg(data.msg, {offset: '6px'});
                    }else {
                        layer.alert(data.msg,{title:'提示',icon: 2});
                    }
                }, function(e) {
                    layer.alert('出問題啦~請稍后再試~',{title:'提示',icon: 2});
                }, false);

            });
        });

ajax提交switch控件

if($('#ispub_add').is(':checked')) {
   ispub_add = "1";
}else{
   ispub_add = "0";
}

表單提交獲取不到字段

<c:choose>
     <c:when test="${order.repstate == 1}">
         <form class="layui-form" id="repForm1">
               <div class="layui-input-block"><button class="layui-btn" lay-submit lay-filter="formRepFilter">立即提交</button></div>
         </form>
     </c:when>
     <c:when test="${order.repstate <= 2}">
         <form class="layui-form" id="repForm2">
         </form>
     </c:when>
     <c:otherwise></c:otherwise>
</c:choose>

多個form表單寫在jstl標簽里面,保證服務器渲染后在瀏覽器端只有一個form標簽。這種情況下可以用

layui.use('form', function(){
    var form = layui.form;
    form.on('submit(formRepFilter)', function(data){
        console.info(data.field);
    });
});

如果一個界面必須同時出現多個form標簽,那就只能用單擊事件觸發serialize();

$('#form').serialize();

點擊左側菜單中間出現對應頁面

html

  <div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">-->
      <ul class="layui-nav layui-nav-tree site-demo-nav main_left" lay-filter="side">
                        <li class="layui-nav-item">
                            <a class="javascript:;" href="javascript:;">
                                <i class="layui-icon" style="top: 3px;">&#xe614;</i><cite>系統管理</cite>
                            </a>
                            <dl class="layui-nav-child">
                                <dd class="">
                                    <a _href="./userinfo/i">
                                        <cite>系統用戶</cite>
                                    </a>
                                </dd>
                                <dd class="">
                                    <a href="javascript:;" _href="./system/pingtai.html">
                                        <cite>平台配置</cite>
                                    </a>
                                </dd>
                            </dl>
                        </li>
                        <li class="layui-nav-item">
                            <a class="javascript:;" href="javascript:;" _href="./audit.html">
                                <i class="layui-icon" style="top: 3px;">&#xe63c;</i><cite>審計管理</cite>
                            </a>
                        </li>
       </ul>
    </div>
  </div>
  <div class="layui-body">
    <!-- 內容主體區域 -->
    <iframe frameborder="0" scrolling="yes" style="width:100%;height:100%" src="" id="lay-content"></iframe>
  </div>

js

$(function(){
   $(".main_left li a").on("click",function(){
      var address =$(this).attr("_href");
      $("#lay-content").attr("src",address);
   });
});

也可以用開源框架x-admin

Layui樹

一定要用layui2.5.5+,否則顯示不出來

    //初始化
    layui.use('tree', function(){
        tree = layui.tree;
        getTreeData();
    });
    /*獲取樹*/
    function getTreeData() {
        $.ajax({
            url: "./permission/selectPermissionTree"
            , data: {}
            , type: "post"
            , dataType: "json"
            , success: function (data) {
                tree.render({
                    elem: '#permissiontree'
                    ,data: data
                    ,edit: ['add', 'update', 'del'] //操作節點的圖標
                    ,click: function(obj){
                        var data = obj.data;
                        $('#moduleid').val(data.id);
                        $('#modulename').val(data.title);
                        $('#path').val(data.href);
                        $('#ordernumber').val(data.ordernumber);

                        layui.use('form', function() {
                            var form = layui.form;
                            //監聽修改提交
                            form.on('submit(formEdit)', function(data){
                                $.ajax({
                                    url: "./permission/updateByPrimaryKeySelective"
                                    , data: data.field
                                    , type: "post"
                                    , dataType: "json"
                                    , success: function (data) {
                                        if (data.code == "success") {
                                            layer.alert(data.msg,{title:'提示',icon: 1},function(index){
                                                layer.close(index);
                                                getTreeData();
                                            });
                                        }else {
                                            layer.alert(data.msg,{title:'提示',icon: 2});
                                        }
                                    }
                                });
                                return false;
                            });
                        });
                    }
                    ,operate: function(obj){
                        var type = obj.type; //得到操作類型:add、edit、del
                        var data = obj.data; //得到當前節點的數據
                        var elem = obj.elem; //得到當前節點元素

                        if(type === 'add'){ //增加節點
                            add(data);
                        } else if(type === 'update'){ //修改節點
                            rename(data);
                        } else if(type === 'del'){ //刪除節點
                            del(data.id);
                        }
                    }
                });
            }

        });
    }

樹復選框回顯

在添加時一定只添加葉子結點,回顯時才不會因為把父節點設置選中導致整個子樹都選中。

添加時值添加子結點toListDF方法是關鍵。

    /**
     * 配置權限
     */
    function allotPermission() {
        var checkData = tree.getChecked('permissiontreeID');
        var modultlist = treeToList(checkData);
        var roleid = $('#roleid_permission').val();

        var data = {moduleids:modultlist.join(','),roleId:roleid};
        $.ax('./permission/addmodulejoinrole', data, 'POST', function(data) {
            if (data.code == "success") {
                layer.alert(data.msg,{title:'提示',icon: 1},function(index){
                    layer.close(index);
                    layer.close(allotLayer);
                    //getTreeData();  //刷新樹
                });
            }else {
                layer.alert(data.msg,{title:'提示',icon: 2});
                getTreeData();  //刷新樹
            }
        }, function(e) {
            layer.alert('出問題啦~請稍后再試~',{title:'提示',icon: 2});
            getTreeData();  //刷新樹
        }, false);
    }

    /**
     * 樹轉list
     */
    function treeToList(tree){
        for(var i in tree){  //遍歷樹的第一層,只有一個根結點
            var node = tree[i];
            list = [];  //結果lsit
            if (node.children.length !== 0) { //第一層加入到list中,因為根結點模塊設置為虛擬結點,所以不用加入
                /*list.push(node.id);*/
                toListDF(node.children, list, node.id);  //遍歷子樹,並加入到list中.
            }
        }
        return list;
    }

    /**
     * 深度優先遍歷樹
     * 一個遞歸方法
     * @params tree:要轉換的樹結構數據
     * @params list:保存結果的列表結構數據,初始傳list = []
     * @params parentId:當前遍歷節點的父級節點id,初始為null(因為根節點無parentId)
     **/
    function toListDF (tree, list, parentId) {
        for (var i in tree) { //遍歷最上層
            //將當前樹放入list中
            var node = tree[i];
            //如果有子結點,再遍歷子結點
            if (node.children.length !== 0) {
                toListDF(node.children, list, node.id)  //遞歸
            }else {
                list.push(node.id);
            }
        }
    }

富文本框

https://www.layui.com/doc/modules/layedit.html

            <textarea id="layedit" style="display: none;"></textarea>
 /*構建富文本編輯器*/ layui.use('layedit', function(){ var layedit = layui.layedit; //構建一個默認的編輯器
                layedit_up_index = layedit.build('content_up', {tool:['strong' //加粗
                        , 'italic' //斜體
                        , 'underline' //下划線
                        , 'del' //刪除線
                        , '|' //分割線
                        , 'left' //左對齊
                        , 'center' //居中對齊
                        , 'right' //右對齊
                        , 'link' //超鏈接
                        , 'unlink' //清除鏈接
 ] }); });

在彈框中構建富文本編輯器時,要先彈出再構建。

自動填充插件

autocomplete

HTML代碼

<input type="text" name="type" id="typeQuery" autocomplete="off" class="layui-input" placeholder="請輸入類型,格式:表名_字段名">

JS代碼

/*引入樣式*/
layui.link('./asset/layui2.5.5/extra/autocomplete.css');

/*配置第三方庫*/
layui.config({
    version: false,
    debug: false,
    base: './asset/layui2.5.5/extra/'
});

/*使用autocomplete*/
layui.use(['jquery', 'autocomplete'], function () {
    var $ = layui.jquery,
        autocomplete = layui.autocomplete;
    autocomplete.render({
        elem: $('#typeQuery')[0],
        url: './setting/getSettingType',
        template_val: '{{d.type}}',
        template_txt: '{{d.type}} <span class=\'layui-badge layui-bg-gray\'>{{d.remark}}</span>',
        onselect: function (resp) {

        }
    });
});

數據格式

數據列表要放在data中,code要為0

成果

X-admin

刷新后tab頁依然存在的問題。x-admin把tab的列表放入localstorage中,刷新時把localstorage清除即可。

        $(function () {
            /*清除localstorage的內容*/
            var storage=window.localStorage;
            storage.clear();
        });

iframe頁打開新的tab頁

首先查看iframe外部打開新的tab頁的js代碼。

然后在iframe內部用window.parent調用iframe外部的js方法。

window.parent.xadmin.add_tab(rowdata.projectName+"收款合同",'./cont_receive/redirect?projectid='+rowdata.id,true);

 


免責聲明!

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



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