Layui前端框架

时间:2024-03-12 08:43:46

官网

https://www.layui.com/

datagrid

加序号列

在table.render的cols参数中加序号列

{field: \'rank\', title: \'序号\',width:60, 
   templet: function(d){
      return d.LAY_TABLE_INDEX+1;
}}

复选框不居中显示问题

.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} 
            });

获取页码和页大小

$(".layui-laypage-skip").find("input").val();  //当前页码值
$(".layui-laypage-limits").find("option:selected").val();  //分页数目

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监控

html

<div class="layui-form-item">
    <label class="layui-form-label">单选框</label>
    <div class="layui-input-block">
        <input type="radio"  lay-filter="sex" name="sex" value="男" title="男" checked="">
        <input type="radio"  lay-filter="sex" name="sex" value="女" title="女">
        <input type="radio"  lay-filter="sex" name="sex" value="禁" title="禁用" disabled="">
    </div>
</div>

js

        layui.use([\'form\', \'layer\', \'jquery\' ], function () {
            $ = layui.jquery;
            var layer = layui.layer,
                form = layui.form;
                //监听多选框点击事件  主要是通过 lay-filter="sex"  来监听
            form.on(\'radio(sex)\', function (data) {
                console.log(data);  //打印当前选择的信息
                if( data.elem.checked){      //判断当前多选框是选中还是取消选中
                    alert(\'当前选中\');
                }else{
                    alert(\'取消选中\')
                }
                var value = data.value;   //  当前选中的value值
            });
        });

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();

选项卡

<script>
        //注意:选项卡 依赖 element 模块,否则无法进行功能性操作
        layui.use(\'element\', function () {
            var element = layui.element;
            element.on(\'tab(tab_box)\', function (data) {
                console.log(data);
                if(data.index == 0 || data.index == 1 || data.index == 2){
                    //index表示选项卡下标
                    $(document).resize()
                }
            });
        });
</script>

<div class="layui-tab layui-tab-brief" lay-filter="tab_box">
  <ul class="layui-tab-title">
    <li class="layui-this">网站设置</li>
    <li>用户管理</li>
    <li>权限分配</li>
  </ul>
  <div class="layui-tab-content">
    <div class="layui-tab-item layui-show">内容1</div>
    <div class="layui-tab-item">内容2</div>
    <div class="layui-tab-item">内容3</div>
  </div>
</div>  

关闭当前tab页面

        //跳转到其他界面
        window.location.href = "${liveurl}";
        //关闭当前窗口
        var lay_id = $(".layui-tab-title .layui-this",parent.document).find(\'.layui-tab-close\').click();

点击左侧菜单中间出现对应页面

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

成果

插件

excel.js导入数据

自动把excel文件读取到内存中,存储为对象数组。需要转换为json格式的字符串以application/json传输到后台。

引入layui_exts/excel.js

Html代码

<input type="file" class="layui-btn layui-btn-primary" id="LAY-excel-import-excel" multiple="multiple">

JS代码

    $(function() {
        // 监听上传文件的事件
        $(\'#LAY-excel-import-excel\').change(function (e) {
            var files = e.target.files;
            try {
                // 方式一:先读取数据,后梳理数据
                LAY_EXCEL.importExcel(files, {}, function (data) {
                    data = LAY_EXCEL.filterImportData(data,{
                        \'name\': \'A\'
                        /*,\'date\': function (v, item, data, rowIndex, newFieldName) {
                            if (rowIndex == 0) {
                                // 直接调用辅助方法格式化,也可以转换为 Date 对象后自行处理
                                return LAY_EXCEL.dateCodeFormat(item[\'B\'], \'YYYY-MM-DD HH:ii:ss\')
                            } else {
                                return item[\'B\'];
                            }
                        }*/
                        , \'phone\': \'B\'
                        , \'facultyName\': \'C\'
                        , \'className\': \'D\'
                    })
                    var teacherData = data[0].Sheet1;
                    if(teacherData[0].name.indexOf(\'教师\') != -1 && teacherData[1].name == \'教师姓名\'){
                        teacherData.splice(0,2);   //删除前两项
                    }else{
                        layer.alert("模板不符合要求,请重新下载模板!");
                    }
                    var teacherjsonData = JSON.stringify(teacherData);
                    $(\'#teacherjsonData\').val(teacherjsonData);
                    //console.log($(\'#teacherjsonData\').val());
                });
            } catch (e) {
                layer.alert(e.message);
            }
        });
    });

用application/json格式上传数据

    layui.use(\'form\', function(){
        var form = layui.form;
        //监听修改提交
        form.on(\'submit(formUpload)\', function(data){

            layer.confirm(\'确认导入教师信息吗?\', {icon: 3, title:\'提示\'}, function(index){
                var teachers = $(\'#teacherjsonData\').val();

                if(teachers==null||teachers==\'\'){
                    layer.alert(\'上传内容为空!\',{title:\'提示\',icon: 2});
                }

                $.ajax({
                    url: "../../back/teacherManager/addBatch"
                    , data: teachers
                    , contentType: "application/json;charset=UTF-8"
                    , type: "post"
                    , dataType: "json"
                    , success: function (data) {
                        if (data.code == "success") {
                            layer.alert(data.msg,{title:\'提示\',icon: 1},function(index){
                                layer.close(editLayer);
                                layer.close(index);
                                layui.form.render();
                                table.reload(\'teacherInfoList\', {
                                    url: "../../back/teacherManager/getAllTeacher"
                                    //,where: {} //设定异步数据接口的额外参数
                                });
                            });
                            $("#form_upload")[0].reset();
                        }else {
                            layer.alert(data.msg,{title:\'提示\',icon: 2});
                        }
                    }
                });
            });
            return false;
        });
    });

发送数据内容如下:

excel.js导出数据

function openexportDataDiv() {
    var loading = layer.msg("正在导出,请稍后...", {
        shade: false,
        time:0
    });
    $.ajax({
        type: \'post\',
        url: \'../../back/teacherManager/getAllTeacher\',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {page:1,limit:Math.pow(2,16)},
        beforeSend: function(request) {
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        },
        success: function(d) {

            var data = LAY_EXCEL.filterExportData(d.data, {loginName:\'loginName\', name:\'name\',phone:\'phone\'
                wxOpenId:function (value, line, data) {
                    var r = \'\';
                    if (value == null || value == \'\' || value == undefined) {
                        return \'未注册\';
                    }else{
                        return \'注册\';
                    }
                }
            });
            data.unshift({
                loginName: \'用户名\',
                name: \'姓名\',
                phone: \'电话\',
                facultyName: \'系\',
                className: \'班级\',
                deptType: \'职务\',
                wxOpenId: \'注册状态\'
            });
            LAY_EXCEL.exportExcel(data, \'教师信息导出.xlsx\', \'xlsx\');
            layer.close(loading);
        },
        error: function(e) {
        }
    });
}

 

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);