bootstrap-treeview.js1是一款強大的樹菜單插件,本文給大家介紹bootstrap treeview的簡單使用。
廢話不多說,直接上干干貨。
1、bootstrap-treeview Github網址:
https://github.com/jonmiles/bootstrap-treeview
2、使用要求:
<!-- 樣式表 --><link href="~/Content/bootstrap.css" rel="stylesheet" /><link href="~/bootstrap-treeview.css" rel="stylesheet" /><!-- JS文件 --><script src="jquery.js"></script><script src="bootstrap-treeview.js"></script>
3、數據格式:(注意了,使用過程中,樹的數據格式可以Json格式,也可以寫死,當然寫死的代碼肯定不靈活。Json格式的字段名一定要按照tree的字段要求,即文本格式text,子節點名稱nodes等)
var tree = [{text: "Parent 1",nodes: [{text: "Child 1",nodes: [{text: "Grandchild 1"},{text: "Grandchild 2"}]},{text: "Child 2"}]},{text: "Parent 2"},{text: "Parent 3"},{text: "Parent 4"},{text: "Parent 5"}];4、簡單使用:
4.1 添加容器:
<div id="tree"></div>
4.2 定義樹結構:(data為Json格式數據,這里采用ajax,從后臺獲取,代碼如下)
<script>$(function () {$.ajax({type: "Post",url: "/Home/GetTreeJson",dataType: "json",success: function (result) {$('#tree').treeview({data: result, // 數據源showCheckbox: true, //是否顯示復選框highlightSelected: true, //是否高亮選中//nodeIcon: 'glyphicon glyphicon-user', //節點上的圖標nodeIcon: 'glyphicon glyphicon-globe',emptyIcon: '', //沒有子節點的節點圖標multiSelect: false, //多選onNodeChecked: function (event,data) {alert(data.nodeId);},onNodeSelected: function (event, data) {alert(data.nodeId);}});},error: function () {alert("樹形結構加載失敗!")}});})</script>注:onNodeChecked 和 onNodeSelected 方法是說明文檔中默認的方法,還有其他的方法,自己自己查閱說明文檔,或者查看 bootstrap-treeview.js 文件,未壓縮的js文件內容非常詳細,易懂。
4.3 Json格式數據源:(采用.net MVC框架,列出簡單的Control代碼)
/// <summary>/// 返回Json格式數據/// </summary>/// <returns></returns>[HttpPost]public JsonResult GetTreeJson(){var nodeA = new List<Node>();nodeA.Add(new Node(4, "A01", null));nodeA.Add(new Node(5, "A02", null));nodeA.Add(new Node(6, "A03", null));var nodeB = new List<Node>();nodeB.Add(new Node(7, "B07", null));nodeB.Add(new Node(8, "B08", null));nodeB.Add(new Node(9, "B09", null));var nodes = new List<Node>();nodes.Add(new Node(1, "A01", nodeA));nodes.Add(new Node(2, "B02", nodeB));nodes.Add(new Node(3, "A03", null));return Json(nodes, JsonRequestBehavior.AllowGet);}/// <summary>/// Tree類/// </summary>public class Node{public Node() { }public Node(int id, string str, List<Node> node){nodeId = id;text = str;nodes = node;}public int nodeId; //樹的節點Id,區別于數據庫中保存的數據Id。若要存儲數據庫數據的Id,添加新的Id屬性;若想為節點設置路徑,類中添加Path屬性public string text; //節點名稱public List<Node> nodes; //子節點,可以用遞歸的方法讀取,方法在下一章會總結}5、總結:
簡單的創建了樹,復雜的功能以及邏輯判斷還需要進一步設計,自己閱讀bootstrap-treeview.js 還是很有啟發和發現的0-0,。
補充:

基于bootstrap-treeview做的一個漂亮的無限分類樹層級聯動菜單1.1版,點擊可以下載源碼
總結
以上所述是小編給大家介紹的bootstrap treeview的簡單使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答