The front-end framework Layui implements dynamic tabs & iframe usage (with source code)

Table of contents

I. Introduction

1. What is the Tab tab

2. What is an iframe tag

3. Use iframe tags

2. Case realization

1. Demand analysis

①Look for the appropriate tab in the online Layui example

②There is no url attribute on the right side of the left click

③Click on the content on the right side of the list on the left to open more questions

④Optimize public files

2. Optimization of Dao layer

3. JSP page construction

4. Case presentation

5. Summary


I. Introduction

1. What is the Tab tab

        Tab (Tab) is a common user interface element used to display multiple content pages in a container. Each tab usually consists of a label and a corresponding content area .

When the user clicks on a tab's label, the corresponding content area is revealed, while the content areas of other tabs are hidden. In this way, users can switch between different pages by clicking on different tabs, thereby providing a better user experience.

        In web development, there are usually multiple ways to implement tabs, such as manually coding using HTML, CSS, and JavaScript, or using existing tab plugins/libraries to simplify the development process. Common tab plugins/libraries include Bootstrap's Tab plugin, jQuery UI's Tabs component, etc.

        Through tabs, users can easily switch between different content on a page, which is very useful in many application scenarios, such as web page navigation menus, setting panels, multi-tab browsers, etc. The appearance and interaction of tabs can be customized according to design needs and user experience .

Tab effect display:

2. What is an iframe tag

An iframe (inline frame) is a tag in HTML used to embed another page or document within a web page.

By using the iframe tag, an independent inline frame can be created in a web page to display external content from a different source or from the same source. This embedded page can be another web page, video, map, advertisement, etc.

iframe tags usually contain the following attributes:

  • src: Specifies the URL of the content to load.
  • width: Specifies the width of the `iframe`.
  • -height: Specifies the height of the `iframe`.
  • frameborder: Specifies whether to display the border.
  • scrolling: Specifies whether to display scroll bars.

The sample code is as follows:

<iframe src="http://www.example.com" width="500" height="300" frameborder="0" scrolling="auto"></iframe>

It should be noted that when using the iframe tag, the embedded content will be displayed in a separate frame, which has certain isolation from the parent page. This makes iframes very useful, such as embedding third-party content in web pages, displaying advertisements, integrating other web applications, etc. But at the same time, we also need to pay attention to security and design considerations to avoid security risks and user experience problems that may be caused by abusing iframes.

3. Use iframe tags

When using an iframe tag, you need to specify the URL or source file of the content to embed and define the corresponding attributes. Here is an example using the `iframe` tag:

<!DOCTYPE html>
<html>
<head>
  <title>嵌入页面示例</title>
</head>
<body>
  <h1>主页面</h1>

  <iframe src="http://t.csdn.cn/ommMR" width="800" height="600" frameborder="0" scrolling="auto"></iframe>

  <p>这是主页面中的其他内容。</p>
</body>
</html>

In this example, iframethe tag embeds a web page from " http://t.csdn.cn/ommMR ". Set the width to 800px and the height to 600px. frameborderThe property is set to 0 to hide the border, and scrollingthe property is set to "auto" to show scrollbars based on whether the content exceeds the frame.

Note that using iframetags requires that the embedded content is trusted and follows security best practices to prevent potential security risks.

Effect demonstration:

2. Case realization

1. Demand analysis

①Look for the appropriate tab in the online Layui example

The following is a static effect display:

②There is no url attribute on the right side of the left click

Since our tool class TreeVo cannot have all the fields in our database, how should we dynamically generate a TreeVo tool class with attribute url? ?

TreeVo tool class

package com.zking.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class TreeVo<T> {
	/**
	 * 节点ID
	 */
	private String id;
	/**
	 * 显示节点文本
	 */
	private String text;
	/**
	 * 节点状态,open closed
	 */
	private Map<String, Object> state;
	/**
	 * 节点是否被选中 true false
	 */
	private boolean checked = false;
	/**
	 * 节点属性
	 */
	private Map<String, Object> attributes;

	/**
	 * 节点的子节点
	 */
	private List<TreeVo<T>> children = new ArrayList<TreeVo<T>>();

	/**
	 * 父ID
	 */
	private String parentId;
	/**
	 * 是否有父节点
	 */
	private boolean hasParent = false;
	/**
	 * 是否有子节点
	 */
	private boolean hasChildren = false;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Map<String, Object> getState() {
		return state;
	}

	public void setState(Map<String, Object> state) {
		this.state = state;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	public List<TreeVo<T>> getChildren() {
		return children;
	}

	public void setChildren(List<TreeVo<T>> children) {
		this.children = children;
	}

	public boolean isHasParent() {
		return hasParent;
	}

	public void setHasParent(boolean isParent) {
		this.hasParent = isParent;
	}

	public boolean isHasChildren() {
		return hasChildren;
	}

	public void setChildren(boolean isChildren) {
		this.hasChildren = isChildren;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public TreeVo(String id, String text, Map<String, Object> state, boolean checked, Map<String, Object> attributes,
                  List<TreeVo<T>> children, boolean isParent, boolean isChildren, String parentID) {
		super();
		this.id = id;
		this.text = text;
		this.state = state;
		this.checked = checked;
		this.attributes = attributes;
		this.children = children;
		this.hasParent = isParent;
		this.hasChildren = isChildren;
		this.parentId = parentID;
	}

	public TreeVo() {
		super();
	}

}

After reading the above code, we can find that although we don’t have the attributes we want, but we have the private Map<String, Object> attributes attribute , then we can directly traverse the level data when converting the level data into parent-child level data Add it to the Map collection, so that this attribute has all the fields of the database table.

③Click on the content on the right side of the list on the left to open more questions

We only need to add a judgment before adding the tab tab. We found that there is a lay-id attribute on the li tag in the tab. We only need to assign our TreeVo id to it, and then pass it every time we click jquery gets the label, if it is not found, it means it is not opened, if it is found, then we will select it.

//点击左侧列表右侧选项卡打开
		function opedTab(title, content, id) {
			//判断是否已经打开
			var node=$('li[lay-id="'+id+'"]');
			//没有找到该标签时就打开
			if(node.length==0){
				//因为element没有获取到要扩大权限(layui.use里有element)
				  element.tabAdd('demo', {
					title : title,
					content :"<iframe frameborder='0' src='"+content+"' scrolling='auto' style='width:100%;height:100%;'></iframe>",
					id : id
				})  
			}
			//有该标签就打开
			element.tabChange('demo', id)
			
		}

④Optimize public files

Because we need to write a lot of ${pageContext.request.contextPath} on the page is very cumbersome, so we can use a tag - base tag

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html ">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<!-- 引入layui.css-->
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/js/layui/css/layui.css">

<!-- 引入layui.js-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/layui/layui.js"></script>

<!-- base标签 -->
<base href="${pageContext.request.contextPath}/">


</head>

</html>

Tips:

<base> A tag is a meta tag in HTML that is used to specify the base URL of all relative paths in the page.

Using  <base> tags can change the base URL of all relative links in the page, which is a global setting. Normally, relative paths are resolved based on the URL of the current page. However, when using  <base> tags, the relative path will be  <base> based on the URL specified in the tag. It should be noted that a page can only have one  <base> tab, and it should be placed at  <head> the top of the tabs .

2. Optimization of Dao layer

package com.xw.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xw.entity.Permission;
import com.zking.util.BaseDao;
import com.zking.util.BuildTree;
import com.zking.util.TreeVo;

/**管理系统左侧列表
 * @author 索隆
 *
 */
public class PermissionDao extends BaseDao<Permission>{
	
	/**获取管理的所有信息(平级数据)
	 * @return
	 * @throws Exception 
	 */
	public List<Permission> list() throws Exception{
		String sql="select * from t_oa_permission";
		return  super.executeQuery(sql, Permission.class, null);
	}

	
	/**将平级数据变成我们需要的父子级数据
	 * @return
	 * @throws Exception 
	 */
	public List<TreeVo<Permission>> menu() throws Exception{
		//存放父子级的容器
		List<TreeVo<Permission>> menu=new ArrayList<TreeVo<Permission>>();
		//拿到平级数据
		List<Permission> list = this.list();
		//遍历平级数据
		for (Permission permission : list) {
			//工具类帮助我们完成父子级关系
			TreeVo<Permission> vo=new TreeVo<Permission>();
			vo.setId(permission.getId()+"");//id
			vo.setParentId(permission.getPid()+"");//父级id
			vo.setText(permission.getName());//列表名称
			
            //优化代码
			//利用一个map集合保存TreeVo没有的属性
			Map<String, Object> map=new HashMap<>();
			//将数据的所有信息保存到map容器中
			map.put("self", permission);
			vo.setAttributes(map);
			
			menu.add(vo);
		}
		
		//通过工具类筛选父级菜单的儿子,String是父级菜单的pid
		return BuildTree.buildList(menu, "-1");
	}
	
	
	
	
}

It was also mentioned in the requirements analysis just now, so I won’t explain too much here, just look at the code directly.

3. JSP page construction

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<%@ include file="common/static.jsp"%>
<script type="text/javascript" src="js/index.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">OA会议系统</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="${pageContext.request.contextPath }/static/images/user/小黑子索隆.jpg"
						class="layui-nav-img">我的
				</a>
					<dl class="layui-nav-child">
						<dd>
							<a href="">修改信息</a>
						</dd>
						<dd>
							<a href="">安全管理</a>
						</dd>
						<dd>
							<a href="login.jsp">退出登录</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">

				</ul>
			</div>
		</div>

		<div class="layui-body">
			<!-- 内容主体区域 -->
			<div class="layui-tab" lay-filter="demo" lay-allowclose="true">
				<ul class="layui-tab-title">
					
				</ul>
				<div class="layui-tab-content">
					
				</div>
			</div>
		</div>

		<div class="layui-footer">
			<!-- 底部固定区域 -->
			底部固定区域
		</div>

	</div>
	<script>
	var element,layer,util,$;

layui.use(['element', 'layer', 'util','jquery'], function(){
	element = layui.element
  ,layer = layui.layer
  ,util = layui.util
  ,$ = layui.jquery;
  

  	$.ajax({
  		url: " Permission.action?methodName=listmenu",
  		type: 'post',
  		dataType: 'json',
  		success: function(data) {
  			//定义一个变量将回显的数据进行拼接,最终追加到指定标签上
  			var str='';
  			$.each(data,function(i,n){
  				str+='<li class="layui-nav-item layui-nav-itemed">';
  				str+=' <a class="" href="javascript:;">'+n.text+'</a>';
  				//判断有无children节点有就遍历
  				if(n.hasChildren){
  					//有children节点拿到children节点
  					var children=n.children;
  						str+='<dl class="layui-nav-child">';
  					$.each(children,function(idx,node){
  						str+='<dd><a href="javascript:;" onclick="opedTab(\''+node.text+'\',\''+node.attributes.self.url+'\',\''+node.id+'\')">'+node.text+'</a></dd>';
  		  			})
  		  				str+='</dl>';
  				}
  				
  				str+='</li>';
  				
  			})
  			//将拼接内容追加到指定ul标签
  			$("#menu").html(str);
  			//渲染ul标签
  			element.render('menu');
  			
  		}
  	})
  
  
});




		//点击左侧列表右侧选项卡打开
		function opedTab(title, content, id) {
			//判断是否已经打开
			var node=$('li[lay-id="'+id+'"]');
			//没有找到该标签时就打开
			if(node.length==0){
				//因为element没有获取到所有要去上面扩大权限
				  element.tabAdd('demo', {
					title : title,
					content :"<iframe frameborder='0' src='"+content+"' scrolling='auto' style='width:100%;height:100%;'></iframe>",
					id : id
				})  
			}
			//有该标签就打开
			element.tabChange('demo', id)
			
			
			
		}
		
		
	</script>
</body>
</html>

4. Case presentation

Only after successful login can you visit our main page 

 Because the url page here has not been written in my project, so 404 is inevitable, don't worry about it! ! !

5. Summary

  • ①Because we need to use element in the method we wrote ourselves, and we didn’t get this element in the method. We need to expand the scope when layui.use (loading module) gets element.
  • ②url does not have this attribute in the TreeVo tool class, so we need to write an article when the flat-level data is converted into parent-child data, add it to the Map, and then assign the Map to the Attributes property in TreeVo, so as to get all the fields of the database table and content.
  • ③ After the tab is opened, it cannot be opened repeatedly, and judgment should be made. If the tab already exists, then I will let it be selected, and if it does not exist, I will open it.

My sharing is over here, welcome to the comment area to discuss and communicate! !

If you find it useful, please give it a thumbs up ♥ ♥

Guess you like

Origin blog.csdn.net/weixin_74318097/article/details/131688079