BootStrap Jstree 樹形菜單的增刪改查的實現(xiàn)源碼
1.首先需下載jstree的插件點擊打開鏈接
2.在頁面引入插件js文件css文件
<link rel="stylesheet" href="plugins/jstree/themes/classic/style.css" rel="external nofollow" > <script type="text/javascript" src="plugins/jstree/_lib/jquery.js"></script> <script type="text/javascript" src="plugins/jstree/_lib/jquery.cookie.js"></script> <script type="text/javascript" src="plugins/jstree/_lib/jquery.hotkeys.js"></script> <script type="text/javascript" src="plugins/jstree/jquery.jstree.js"></script>
3.初始化控件
1)html
<div id="demo2" class="demo" style="height:100px;"></div>
2)js 使用 demo2來初始化樹形控件
<script type="text/javascript" class="source below">
$(function() {
$("#demo2").jstree(
{
"json_data" : {
"ajax" : {
"url" : "http://localhost:8080/MemberManager/DepartmentTreeJson",
"data" : function(n) {
// the result is fed to the AJAX request `data` option
return {
"operation" : "get_children",
"id" : n.attr ? n
.attr(
"id")
.replace(
"node_",
"")
: 1
};
}
}
},
"plugins" : [
"themes",
"json_data",
"ui",
"crrm",
"contextmenu",
"search" ],
})
.bind("loaded.jstree",
function(event, data) {
})
.bind(
"select_node.jstree",
function(event, data) {
if (data.rslt.obj
.attr("id") != undefined) {
}
})
.bind(
"remove.jstree",
function(e, data) {
data.rslt.obj.each(function() {
$.ajax({
async : false,
type : 'POST',
url : "http://localhost:8080/MemberManager/CreateNodeForDepartment",
data : {
"operation" : "remove_node",
"id" : this.id.replace("node_", "")
},
success : function(r) {
if (!r.status) {
data.inst.refresh();
}
}
});
});
})
.bind(
"remove.jstree",
function(e, data) {
data.rslt.obj.each(function() {
$.ajax({
async : false,
type : 'POST',
url : "http://localhost:8080/MemberManager/CreateNodeForDepartment",
data : {
"operation" : "remove_node",
"id" : this.id
.replace(
"node_",
"")
},
success : function(
r) {
if (!r.status) {
data.inst.refresh();
}
}
});
});
})
.bind(
"create.jstree",
function(e, data) {
$.post(
"http://localhost:8080/MemberManager/CreateNodeForDepartment",
{
"operation" : "create_node",
"id" : data.rslt.parent
.attr(
"id")
.replace(
"node_",
""),
"position" : data.rslt.position,
"title" : data.rslt.name,
"type" : data.rslt.obj
.attr("rel")
},
function(r) {
if (r.status) {
$(data.rslt.obj).attr("id", "node_" + r.id);
} else {
data.inst.refresh();
$.jstree.rollback(data.rlbk);
}
});
})
.bind(
"rename.jstree",
function(e, data) {
$.post(
"http://localhost:8080/MemberManager/CreateNodeForDepartment",
{
"operation" : "rename_node",
"id" : data.rslt.obj
.attr(
"id")
.replace(
"node_",
""),
"title" : data.rslt.new_name
},
function(r) {
if (!r.status) {
data.inst.refresh();
$.jstree.rollback(data.rlbk);
}
});
})
// 1) the loaded event fires as soon as data is parsed and inserted
// 2) but if you are using the cookie plugin or the core `initially_open` option:
.one("reopen.jstree",
function(event, data) {
})
// 3) but if you are using the cookie plugin or the UI `initially_select` option:
.one("reselect.jstree",
function(event, data) {
});
});
</script>
</pre>4.代碼解析<p></p><p><pre name="code" class="java">
import java.util.List;
public class Department {
// 部門id
private String departmentid;
// 部門名稱
private String name;
// 父級部門ID
private String parentid;
//同級之間的排序。排序id 小的排前面
private String orders;
//子節(jié)點
private List<Department> childNode;
public List<Department> getChildNode() {
return childNode;
}
public void setChildNode(List<Department> childNode) {
this.childNode = childNode;
}
public String getDepartmentid() {
return departmentid;
}
public void setDepartmentid(String departmentid) {
this.departmentid = departmentid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getOrders() {
return orders;
}
public void setOrders(String orders) {
this.orders = orders;
}
@Override
public String toString(){
return "[departmentID:"+this.departmentid+
"departmentName:"+this.name+
"parentID:"+this.parentid+"orders:"+this.orders+"]";
}
}
4.代碼解析
插件初始化我這里使用了插件的兩個參數(shù)json_data,以及plugins注意看代碼結(jié)構(gòu)

4.1上圖兩個部分即初始化部分重點解釋下plugins這個參數(shù)是jstree整合插件的地方theme表示主題,json_data將上文定義的json_data也就
是Ajax從后要獲取json數(shù)據(jù)返回到前臺頁面。contextmenu,是鼠標(biāo)右鍵在樹形節(jié)點上會彈出增刪改查的菜單。
4.2 json數(shù)據(jù)的格式
先看展示

這是一個可以無限極下分的菜單,我們可以根據(jù)上圖的目錄結(jié)構(gòu)對照下面的json數(shù)據(jù)結(jié)構(gòu)來看,這樣會更清晰。
{"data":"軟件及數(shù)據(jù)","attr":{"id":"e59365b9-7b2a-43a3-b10a-cfe03d5eb004"},
"children":[
{"data":"創(chuàng)新組","attr":{"id":"73919359-2a1b-4ee7-bcc2-56949e8560e8"},
"children":[
{"data":"大數(shù)據(jù)","attr":{"id":"a7ea6a0f-0b78-4064-803b-f2e0a95d914f"},
"children":[
{"data":"研發(fā)","attr":{"id":"fc20e438-e7b9-4cca-be6a-49965daab528"},"children":[]}]}]},
{"data":"項目管理","attr":{"id":"e1bdae71-6cfb-4e8c-ab29-a3eb03b9961d"},"children":[]}
]
},
4.4組裝json數(shù)據(jù),我使用的是首先查找到所有的父節(jié)點即parentid=1的時候,然后遞歸將所有的子節(jié)點加到List<chiledren>對象里面,緊接著再通過循環(huán)遞歸組裝無限極菜單json數(shù)據(jù)下面看數(shù)據(jù)庫數(shù)據(jù)結(jié)構(gòu)
import java.util.List;
public class Department {
// 部門id
private String departmentid;
// 部門名稱
private String name;
// 父級部門ID
private String parentid;
//同級之間的排序。排序id 小的排前面
private String orders;
//子節(jié)點
private List<Department> childNode;
public List<Department> getChildNode() {
return childNode;
}
public void setChildNode(List<Department> childNode) {
this.childNode = childNode;
}
public String getDepartmentid() {
return departmentid;
}
public void setDepartmentid(String departmentid) {
this.departmentid = departmentid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getOrders() {
return orders;
}
public void setOrders(String orders) {
this.orders = orders;
}
@Override
public String toString(){
return "[departmentID:"+this.departmentid+
"departmentName:"+this.name+
"parentID:"+this.parentid+"orders:"+this.orders+"]";
}
}
4.5 此處servlet為客戶端提供jstree的json_data。就是在初始化控件時候有ajax調(diào)用這個servlet獲取json數(shù)據(jù)并返回給json_data
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.goldwind.www.service.DepartmentService;
import cn.goldwind.www.serviceimpl.DepartmentServiceImpl;
public class DepartmentTreeJson extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public DepartmentTreeJson() {
super();
}
@Override
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
DepartmentService deptService=new DepartmentServiceImpl();
//此處調(diào)用創(chuàng)建樹節(jié)點的方法
StringBuilder json=deptService.createTreeNode();
json.deleteCharAt(json.length()-1);
System.out.println(json);
out.print("["+json+"]");
out.flush();
out.close();
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
@Override
public void init() throws ServletException {
// Put your code here
}
}
4.6上面servlet我們看下createTreeNode方法
這里是創(chuàng)建json的核心。
1)首先獲取所有的(parent=1)根節(jié)點
@Override
public StringBuilder createTreeNode() {
//創(chuàng)建部門集合
List<Department> departments = new ArrayList<Department>();
//放置所有的根節(jié)點部門實體
departments = queryByParentID("1");
if (departments != null) {
return json(departments);
}
return null;
}
public StringBuilder json(List<Department> departments) {
for (int i = 0; i < departments.size(); i++) {
json.append('{');
json.append("\"data\":\"").append(departments.get(i).getName())
.append("\",");
json.append("\"attr\":{\"id\":\"").append(departments.get(i).getDepartmentid()).append("\"},");
List<Department> deptchild = queryByParentID(departments.get(i)
.getDepartmentid());
json.append("\"children\":");
json.append('[');
if (deptchild != null) {
json(deptchild);
if("1".equals(departments.get(i).getParentid())){
json.deleteCharAt(json.length()-1);
json.append(']');
json.append('}');
json.append(',');
}if(!"1".equals(departments.get(i).getParentid())&&deptchild!=null){
json.deleteCharAt(json.length()-1);
json.append(']');
json.append('}');
json.append(',');
}
} else{
json.append(']');
json.append('}');
json.append(',');
}
}
return json;
}
@Override
public List<Department> queryByParentID(String parentID) {
BaseDaoTemplate bd = new BaseDaoTemplate();
List<Department> departments = new ArrayList<Department>();
String sql = "select departmentid,name,parentid,orders from department where parentid=? ";
List<Object> params = new ArrayList<Object>();
params.add(parentID);
departments = bd.findAllData(Department.class, sql, params);
if (departments.size() > 0) {
return departments;
}
return null;
}
4.7
1.如何創(chuàng)建節(jié)點通過右鍵點擊樹形菜單彈出增加移除等操作(需在plugins里面加入contextmenu 這個例子就有)
2.綁定jstree的操作,此處以增加節(jié)點為例不一一例舉

原理;通過點擊創(chuàng)建按鈕(contextMenu)即選定樹節(jié)點右鍵彈出按鈕。調(diào)用上圖的方法,上圖方法post方法通過ajax請求后臺數(shù)據(jù)把創(chuàng)建的樹節(jié)點保存到數(shù)據(jù)庫,
operation:操作的方式(創(chuàng)建,移除,修改。。);
id:當(dāng)前節(jié)點的id 即你創(chuàng)建下一個節(jié)點的parentID。
title:創(chuàng)建的新節(jié)點的名稱
有這些數(shù)據(jù)就可以字啊后臺獲取數(shù)據(jù)然后增加到數(shù)據(jù)庫。
4.8 創(chuàng)建 servlet處理所有的操作(創(chuàng)建,移除,修改。。)
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.goldwind.www.pojo.Department;
import cn.goldwind.www.service.DepartmentService;
import cn.goldwind.www.serviceimpl.DepartmentServiceImpl;
public class CreateNodeForDepartment extends HttpServlet {
private static final long serialVersionUID = 1L;
public CreateNodeForDepartment() {
super();
}
@Override
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
DepartmentService deptService=new DepartmentServiceImpl();
if("rename_node".equals(request.getParameter("operation"))){
String id=request.getParameter("id");
String title=request.getParameter("title");
Department dept=new Department();
dept.setDepartmentid(id);
deptService.modifyDepartment(dept, title);
}else if("create_node".equals(request.getParameter("operation"))){
String id=request.getParameter("id");
String title=request.getParameter("title");
Department dept=new Department();
dept.setDepartmentid(UUID.randomUUID().toString());
dept.setName(title);
dept.setParentid(id);
deptService.insertDepartment(dept);
}else if("remove_node".equals(request.getParameter("operation"))){
String id=request.getParameter("id");
Department dept=new Department();
dept.setDepartmentid(id);
deptService.deleteDepartment(dept);
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
@Override
public void init() throws ServletException {
// Put your code here
}
}
好了這就完成了,當(dāng)然這里面的樹也是可以自定義圖標(biāo),自定義按鈕等操作,具體可以自己去探究。
以上所述是小編給大家介紹的BootStrap Jstree 樹形菜單的增刪改查的實現(xiàn)源碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
hadoop?詳解如何實現(xiàn)數(shù)據(jù)排序
在很多業(yè)務(wù)場景下,需要對原始的數(shù)據(jù)讀取分析后,將輸出的結(jié)果按照指定的業(yè)務(wù)字段進行排序輸出,方便上層應(yīng)用對結(jié)果數(shù)據(jù)進行展示或使用,減少二次排序的成本2022-02-02
多線程計數(shù),怎么保持計數(shù)準(zhǔn)確的方法
這篇文章主要介紹了多線程計數(shù)的方法,有需要的朋友可以參考一下2014-01-01
SpringCloud微服務(wù)集成Dubbo的詳細過程
Apache?Dubbo?是一款易用、高性能的?WEB?和?RPC?框架,同時為構(gòu)建企業(yè)級微服務(wù)提供服務(wù)發(fā)現(xiàn)、流量治理、可觀測、認(rèn)證鑒權(quán)等能力、工具與最佳實踐,這篇文章主要介紹了SpringCloud微服務(wù)集成Dubbo,需要的朋友可以參考下2024-03-03
SpringBoot電腦商城項目刪除收貨地址的實現(xiàn)方法
這篇文章主要介紹了SpringBoot項目--電腦商城刪除收貨地址功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

