官方網站:Dynatree
下面將會整理一些常用的功能,來做為範例。
$(function(){ loadTree(); //建立子目錄 $("#btnAddNode").click(function(){ //取得被點選節點 var node = $("#tree").dynatree("getActiveNode"); if( !node ){ alert("請點選節點"); }else{ addTreeNode(node.data.key); reloadTree(); } }); //刪除目錄 $("#btnDeleteNode").click(function(){ //取得被點選節點 var node = $("#tree").dynatree("getActiveNode"); if( !node ){ alert("請點選節點"); }else if(node.getLevel()==1){ alert("根節點無法刪除"); }else if(node.hasChildren()){ alert("尚有子節點無法刪除"); }else if(confirm("確定刪除?")){ deleteTreeNode(node.data.key); reloadTree(); } }); }); function loadTree(){ $("#tree").dynatree({ initAjax: { url: "tree.do?method=list" }, onActivate: function(node) { //點擊節點觸發 alert(node.data.key); }, onSelect: function(select, node) { //取得被勾選的節點 var selNodes = node.tree.getSelectedNodes(); var selKeys = $.map(selNodes, function(node){ return node.data.key; }); alert(selKeys.join(",")); }, onPostInit: function(isReloading, isError) { //樹載完後 $("#tree").dynatree("getRoot").visit(function(node){ //將節點全選 node.select(true); } } checkbox: true, minExpandLevel: 2 //預設展開層數 }); } //重新載入 function reloadTree(){ var tree = $("#tree").dynatree("getTree"); tree.reload(); } function addTreeNode(parentID){ var data = "parentID="+parentID; $.ajax({ type: 'POST', url: "tree.do?method=add", data: data, dataType: "txt", async:false }); } function deleteTreeNode(nodeID){ var data = "nodeID="+nodeID; $.ajax({ type: 'POST', url: "tree.do?method=delete", data: data, dataType: "txt", async:false }); }