目录
一、tab选项卡
1.查找layui的选项卡页面布局代码-静态
2.添加动态选项卡
3.将选项卡名称换成菜单名
4.重复的tab选项卡不添加,改为选中
5.跳转页面--iframe
二、进一步完善上一期的登录
本期内容基于⬇⬇⬇⬇⬇上期内容/weixin_67450855/article/details/125617088?spm=1001..3001.5502
一、tab选项卡
1.查找layui的选项卡页面布局代码-静态
老规矩,咱们还是先上官网找到所需要的项目源码,拷贝到需要用到的地方,如下选项卡显示之处⬇
如下内容是我在官网拷贝的所需代码
<div class="layui-body"><!-- 内容主体区域 --><div class="layui-tab" lay-filter="demo" lay-allowClose="true"><ul class="layui-tab-title"><li class="" lay-id="11">首页</li></ul><div class="layui-tab-content"><div class="layui-tab-item layui-show">1</div></div></div></div>
初步运行效果⬇⬇
2.接下来咱们添加动态选项卡
源码
<script type="text/javascript">let $,element;layui.use(['jquery','element'],function(){$ = layui.jquery,element = layui.element;$.ajax({url:"${pageContext.request.contextPath}/permission.action?methodName=menus",dataType:'json',success:function(data){console.log(data)let html = '';$.each(data,function(i,n){html +='<li class="layui-nav-item layui-nav-itemed">';html +=' <a class="" href="javascript:;">'+data[i].text+'</a>';//判断当前一级节点是否存在节点if(data[i].hasChildren){html +=' <dl class="layui-nav-child">';let childern = data[i].children;$.each(childern,function(index,node){html+=' <dd><a href="javascript:;" onClick="openTab()">'+childern[index].text+'</a></dd>';})html +=' </dl>';}html +='</li>';});$("#menu").html(html);}})});function openTab(){element.tabAdd('demo', {title: '新选项'+ (Math.random()*1000|0) //用于演示,content: '内容'+ (Math.random()*1000|0),id: new Date().getTime() //实际使用一般是规定好的id,这里以时间戳模拟下})}</script>
运行如图⬇⬇⬇⬇
3.将选项卡名称换成菜单名
源码
<script type="text/javascript">let $,element;layui.use(['jquery','element'],function(){$ = layui.jquery,element = layui.element;$.ajax({url:"${pageContext.request.contextPath}/permission.action?methodName=menus",dataType:'json',success:function(data){console.log(data)let html = '';$.each(data,function(i,n){html +='<li class="layui-nav-item layui-nav-itemed">';html +=' <a class="" href="javascript:;">'+data[i].text+'</a>';//判断当前一级节点是否存在节点if(data[i].hasChildren){html +=' <dl class="layui-nav-child">';let childern = data[i].children;$.each(childern,function(index,node){html+=' <dd><a href="javascript:;" onClick="openTab(\''+childern[index].text+'\',\''+childern[index].attributes.self.url+'\',\''+childern[index].id+'\')">'+childern[index].text+'</a></dd>';})html +=' </dl>';}html +='</li>';});$("#menu").html(html);}})});function openTab(title,url,id){// 新增一个Tab项element.tabAdd('demo', {title : title,//用于演示content : url,id : id}) } </script>
PermissionDao也跟着进行改动
package com.zking.dao;import java.util.ArrayList;import java.util.List;import com.zking.entity.Permission;import com.zking.util.BaseDao;import com.zking.util.BuildTree;import com.zking.util.PageBean;import com.zking.util.R;import com.zking.util.TreeVo;public class PermissionDao extends BaseDao<Permission>{//查询t_oa_permission表中的数据public List<Permission> executeQuery(Permission permission, PageBean pageBean) throws Exception {String sql="SELECT * from t_oa_permission";return super.executeQuery(sql, Permission.class, pageBean);}public List<TreeVo<Permission>> menus(Permission permission, PageBean pageBean) throws Exception {List<TreeVo<Permission>> trees=new ArrayList<TreeVo<Permission>>();//从数据库中拿到的菜单数据,此时数据都是平级的,不具备父子关系List<Permission> list = this.executeQuery(permission, pageBean);for (Permission p : list) {TreeVo<Permission> vo=new TreeVo<>();vo.setId(p.getId()+"");vo.setText(p.getName());//节点的名字vo.setParentId(p.getPid()+"");//将url放入treevo中,但是treevo中又没有专门的url属性,此时可以将整个permission都放到集合中,设置treevovo.setAttributes(new R().data("self", p));trees.add(vo);}return BuildTree.buildList(trees, "-1");}}
页面效果
此时的页面效果差不多OK了,不过还有可以优化的地方,比如当我点击重复的菜单时,选项卡会不会显示重复???答案一定是会!那该怎么会才能避免这个问题,看⬇⬇⬇⬇
4.重复的tab选项卡不添加,改为选中
咱们只需要将openTab方法进行if判断即可,这样再次点击菜单,选项卡不会出现重复😜
function openTab(title,url,id){let $node=$("li[lay-id='"+id+"']");debugger;//前端断点if($node.length==0){// 新增一个Tab项element.tabAdd('demo', {title : title,//用于演示content : url,id : id}) }element.tabChange('demo', id); }
5.跳转页面--iframe
content : "<iframe frameborder='0' src='"+url+"' scrolling='auto'style='width:100%;height:100%;'></iframe>"
function openTab(title,url,id){let $node=$("li[lay-id='"+id+"']");debugger;//前端断点if($node.length==0){// 新增一个Tab项element.tabAdd('demo', {title : title,//用于演示content : "<iframe frameborder='0' src='"+url+"' scrolling='auto' style='width:100%;height:100%;'></iframe>",id : id}) }element.tabChange('demo', id); }
这里我新建立一个界面,为演示跳转
点击会议发布菜单
二、进一步完善上一期的登录
实体类
package com.zking.entity;public class User {private Long id;private String name;private String loginName;private String pwd;private Long rid;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public Long getRid() {return rid;}public void setRid(Long rid) {this.rid = rid;}public User() {super();// TODO Auto-generated constructor stub}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", loginName=" + loginName + ", pwd=" + pwd + ", rid=" + rid + "]";}}
user实体dao方法
package com.zking.dao;import java.util.List;import com.zking.entity.User;import com.zking.util.BaseDao;public class UserDao extends BaseDao<User> {public User login(User user) throws Exception {String sql="select * from t_oa_user where loginName = '"+user.getLoginName()+"' and pwd = '"+user.getPwd()+"'";//根据sql查询符合条件的用户,通常只会返回一条数据List<User> users = super.executeQuery(sql, User.class, null);return users == null || users.size() == 0 ? null : users.get(0);}}
UserAction
package com.zking.web;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.zking.dao.UserDao;import com.zking.entity.User;import com.zking.framework.ActionSupport;import com.zking.framework.ModelDriver;import com.zking.util.R;import com.zking.util.ResponseUtil;/*** 处理前台的请求* 实现子控制器* @author Administrator**/public class UserAction extends ActionSupport implements ModelDriver<User>{private User user=new User();//接收前台所有参数值private UserDao userDao=new UserDao();//进一步改造登录 调用登录dao方法/*//写一个方法,处理前台的请求public String login(HttpServletRequest req, HttpServletResponse resp) {//定义一个map集合Map<String, Object> map=new HashMap<String, Object>();//假设在页面输入用户/密码为张三、123456;则登录成功反之不成功if("zhangsan".equals(user.getUsername()) && "123456".equals(user.getPassword())) {//向前台响应数据 登录成功map.put("code", 200);map.put("msg", "成功");}else {//登录失败map.put("code", 0);map.put("msg", "账户密码错误");}try {ResponseUtil.writeJson(resp, map);} catch (Exception e) {e.printStackTrace();}return null;}*///简化改造版//写一个方法,处理前台的请求/*public String login(HttpServletRequest req, HttpServletResponse resp) {try {//假设在页面输入用户/密码为张三、123456;则登录成功反之不成功if("zhangsan".equals(user.getUsername()) && "123456".equals(user.getPassword())) {ResponseUtil.writeJson(resp, new R().data("code", 200).data("msg", "成功"));}else {ResponseUtil.writeJson(resp, new R().data("code", 0).data("msg", "失败"));}} catch (Exception e) {e.printStackTrace();}return null;}*///再进一步改造public String login(HttpServletRequest req, HttpServletResponse resp) {try {User u=userDao.login(user);//通过账户名密码查到了用户记录if(u!=null) {ResponseUtil.writeJson(resp, R.ok(200, "登录成功"));}else {ResponseUtil.writeJson(resp, R.ok(0, "用户名密码错误"));}} catch (Exception e) {e.printStackTrace();try {ResponseUtil.writeJson(resp, R.ok(0, "用户名密码错误"));} catch (Exception e2) {e2.printStackTrace();}}return null;}@Overridepublic User getModel() {return user;}}
登录页面前端代码
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!-- 导入公共界面 --><%@ include file="common/header.jsp" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><link rel="stylesheet" rev="stylesheet" href="${pageContext.request.contextPath }/static/css/iconfont.css" type="text/css" media="all"><link rel="stylesheet" rev="stylesheet" href="${pageContext.request.contextPath }/static/css/login.css" type="text/css" media="all"><!-- 导入login.js --><script scr="static/js/login.js"></script><style> body{color:#;}a{color:#;}a:hover{color:#;}.bg-black{background-color:#;}.tx-login-bg{background:url(static/images/bg.jpg) no-repeat 0 0;}</style></head><body class="tx-login-bg"><div class="tx-login-box"><div class="login-avatar bg-black"><i class="iconfont icon-wode"></i></div><ul class="tx-form-li row"><li class="col-24 col-m-24"><p><input type="text" id="username" placeholder="登录账号" class="tx-input"></p></li><li class="col-24 col-m-24"><p><input type="password" id="password" placeholder="登录密码" class="tx-input"></p></li><li class="col-24 col-m-24"><p class="tx-input-full"><button id="login" class="tx-btn tx-btn-big bg-black">登录</button></p></li><li class="col-12 col-m-12"><p><a href="#" class="f-12 f-gray">新用户注册</a></p></li><li class="col-12 col-m-12"><p class="ta-r"><a href="#" class="f-12 f-gray">忘记密码</a></p></li></ul></div></body></html>
聪明的朋友一定发现了,为啥这登录界面都没有向后台发送请求或者是接收后台请求之类的代码嘞?对滴,因为我们要用更妥善更专业滴方法来编辑代码
注意看⬇⬇⬇
header ⬇⬇⬇
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!-- 引入 layui.css --><link rel="stylesheet" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css"><!-- 引入 layui.js --><script src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script><!-- 指定整个项目的根路径 --><base href="${pageContext.request.contextPath }/" /><title>小坤工作室</title>
login.js
layui.use(['jquery','layer'],function(){let $=layui.jquery,layer=layui.layer;$("#login").click(function(){$.ajax({url:"user.action?methodName=login",dataType:'json',data:{loginName:$("#username").val(),pwd:$("#password").val()},success:function(data){//console.log(data);if(data.code==200){layer.alert(data.msg,{icon:1});//登录成功,跳到主页location.href='main.jsp';}else{layer.alert(data.msg,{icon:2});}}});});});
我们测试一下吧,用数据库中张三的用户名,密码登录
输入一个错误的密码
用户名密码输入正确,登录后就跳到主页面了
main.js
let $,element;layui.use(['jquery','element'],function(){$=layui.jquery,element=layui.element;$.ajax({url:'permission.action?methodName=menus',dataType:'json',success:function(data){console.log(data);let htmlstr='';$.each(data,function(i,n){htmlstr+='<li class="layui-nav-item layui-nav-itemed">';htmlstr+=' <a class="" href="javascript:;">'+data[i].text+'<a/>';//判断当前一级节点是否存在子节点if(data[i].hasChildren){htmlstr+='<dl class="layui-nav-child">';let children=data[i].children;$.each(children,function(index,node){htmlstr+='<dd><a href="javascript:;"onClick="openTabs(\''+children[index].text+'\',\''+children[index].attributes.self.url+'\',\''+children[index].id+'\');">'+children[index].text+'</a></dd>';})htmlstr+='</dl>';}htmlstr+='</li>';});$("#menu").html(htmlstr)}});});//1.查找LayUI的选项卡页面布局代码--静态//2.动态的添加选项卡//3.将选项卡名称换成菜单名//4.重复的tab选项卡不添加,改为已选中//5.跳转页面function openTabs(title,url,id){let $node=$("li[lay-id='"+id+"']");debugger;if($node.length==0){//新增一个Tab项element.tabAdd('demo', {title: title //用于演示,content: "<iframe frameborder='0' src='"+url+"' scrolling='auto' style='width:100%;height:100%;'></iframe>",id: id //实际使用一般是规定好的id,这里以时间戳模拟下})}element.tabChange('demo',id);}
主界面main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@include file="common/header.jsp" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><!-- 导入login.js --><script scr="static/js/main.js"></script></head><body><div class="layui-layout layui-layout-admin"><div class="layui-header"><div class="layui-logo layui-hide-xs layui-bg-black">layout demo</div><!-- 头部区域(可配合layui 已有的水平导航) --><ul class="layui-nav layui-layout-left"><!-- 移动端显示 --><li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft"><i class="layui-icon layui-icon-spread-left"></i></li><!-- Top导航栏 --><li class="layui-nav-item layui-hide-xs"><a href="">nav 1</a></li><li class="layui-nav-item layui-hide-xs"><a href="">nav 2</a></li><li class="layui-nav-item layui-hide-xs"><a href="">nav 3</a></li><li class="layui-nav-item"><a href="javascript:;">nav groups</a><dl class="layui-nav-child"><dd><a href="">menu 11</a></dd><dd><a href="">menu 22</a></dd><dd><a href="">menu 33</a></dd></dl></li></ul><!-- 个人头像及账号操作 --><ul class="layui-nav layui-layout-right"><li class="layui-nav-item layui-hide layui-show-md-inline-block"><a href="javascript:;"><img src="///crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg" class="layui-nav-img">tester</a><dl class="layui-nav-child"><dd><a href="">Your Profile</a></dd><dd><a href="">Settings</a></dd><dd><a href="login.jsp">Sign out</a></dd></dl></li><li class="layui-nav-item" lay-header-event="menuRight" lay-unselect><a href="javascript:;"><i class="layui-icon layui-icon-more-vertical"></i></a></li></ul></div><div class="layui-side layui-bg-black"><div class="layui-side-scroll"><!-- 左侧导航区域(可配合layui已有的垂直导航) --><ul id="menu" class="layui-nav layui-nav-tree" lay-filter="menu"><li class="layui-nav-item layui-nav-itemed"><a class="" href="javascript:;">会议管理</a><dl class="layui-nav-child"><dd><a href="javascript:;">发布会议</a></dd><dd><a href="javascript:;">我的会议</a></dd><dd><a href="javascript:;">会议通知</a></dd><dd><a href="">历史会议</a></dd></dl></li><li class="layui-nav-item"><a href="javascript:;">menu group 2</a><dl class="layui-nav-child"><dd><a href="javascript:;">list 1</a></dd><dd><a href="javascript:;">list 2</a></dd><dd><a href="">超链接</a></dd></dl></li><li class="layui-nav-item"><a href="javascript:;">click menu item</a></li><li class="layui-nav-item"><a href="">the links</a></li></ul></div></div><div class="layui-body"><div class="layui-tab" lay-filter="demo" lay-allowclose="true"><ul class="layui-tab-title"><li class="layui-this" lay-id="11">首页</li></ul><div class="layui-tab-content"><div class="layui-tab-item layui-show">1</div></div></div></div><div class="layui-footer"><!-- 底部固定区域 -->底部固定区域</div></div></body></html>
拜拜~累了困了