共计 1996 个字符,预计需要花费 5 分钟才能阅读完成。
如图,通过 jsTree 实现动态菜单栏
阅读 jsTree 的官方文档之后,你会知道,它有很多实现方式,我下面使用的是 Ajax 请求,从后台获取 json 数据返回给 jsTree。jsTree 的官网:https://www.jstree.com/
点击页面的 Download 按钮,下载并解压之后,将 dist 下的文件都复制到你自己的项目中
前端 html, 只保留了关键代码
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<title></title> | |
<!-- Tell the browser to be responsive to screen width --> | |
<meta | |
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" | |
name="viewport"> | |
<!-- Bootstrap 3.3.7 --> | |
<link rel="stylesheet" | |
href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> | |
</head> | |
<body class="hold-transition skin-blue sidebar-mini"> | |
<div class="wrapper"> | |
<!-- 侧边栏【开始】--> | |
<aside class="main-sidebar" id="main-sidebar"> | |
<section class="sidebar"> | |
<ul class="sidebar-menu" data-widget="tree"> | |
<li class="header"> 菜单栏 </li> | |
</ul> | |
<!-- 放置菜单的 div --> | |
<div class="sidebar-menu box-header" style="margin-top: 10px;" | |
id="menu"></div> | |
<img id="sidebar-footer" src="vince/images/QRcode.jpg" | |
style="position: fixed; bottom: 0; width: 200px; height: 200px; padding: 20px;" | |
alt="Logo"> | |
</section> | |
</aside> | |
<!-- 侧边栏【结束】--> | |
<div id="content-wrapper"></div> | |
</div> | |
<!-- jQuery 3 --> | |
<!-- <script src="bower_components/jquery/dist/jquery.min.js"></script> --> | |
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script> | |
<!-- Bootstrap 3.3.7 --> | |
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script> | |
<!-- jstree --> | |
<script type="application/javascript" src="dist/js/jstree.js"></script> | |
<script type="text/javascript"> | |
// 加载菜单【开始】var url = "menu/select"; | |
$(function() {$('#menu') | |
.jstree({ | |
"core" : { | |
'data' : { | |
'url' : url, | |
'data' : function(node) {return node;} | |
}, | |
"themes" : { | |
"ellipsis" : true | |
// 文字多时省略 | |
}, | |
}, | |
"plugins" : ["wholerow", "types", "themes"] | |
}) | |
.on( | |
'select_node.jstree', | |
function(event, data) { | |
// 添加点击标签的方法 | |
loadMainContent(data.node.original.href); | |
}); | |
}); | |
// 加载菜单【结束】function loadMainContent(param) {if ($("body").hasClass("sidebar-open")) {$(".sidebar-toggle").click();} | |
$("#content-wrapper").load(param); | |
} | |
</script> | |
</body> | |
</html> |
后台返回前台的 json 格式,根节点的 parent 一定是“#”否则无法识别,子节点的 parent 是对应的根节点的 id
数据存储格式
正文完
发表至: javascript
2019-06-06