Tree介紹
樹形結構,是程式開發,不可缺少的元件之一。ExtJs中的樹,功能強大美觀實用。功能齊全,拖拉,排序,非同步載入等等。
在ExtJs4中Tree和Grid具有相同的父類,因此Grid具有的特性和外掛在Tree上也能用。
簡單的Tree
程式碼:
<head> <title></title> <link href="/ExtUI/ExtJs4.2.1/resources/css/ext-all.css" rel="stylesheet" type="text/css" /> <link href="/ExtUI/mecss/UIicon.css" rel="stylesheet" type="text/css" /> <script src="/ExtUI/ExtJs4.2.1/ext-all.js" type="text/javascript"></script> <script src="/ExtUI/ExtJs4.2.1/locale/ext-lang-zh_CN.js" type="text/javascript"></script> <script type="text/javascript"> Ext.onReady(function () { //型錄樹Store var treeStore = Ext.create('Ext.data.TreeStore', { proxy: { type: 'ajax', url: '/Tools/106.ashx?method=getCatalogItem&cataId=' + 886 }, fields: ['text', 'id', 'leaf', 'cataId'] }); //型錄樹 var CatalogTtree = Ext.create('Ext.tree.Panel', { store: treeStore, border: false, //邊框 renderTo: Ext.getBody(), enableDD: true, rootVisible: false, //隱藏根節點 useArrows:true, //樹節點使用箭頭 containerScroll: true, collapsible: false, autoScroll: false, //singleExpand:true //展示單個子節點,其它的子節點合併。 }); CatalogTtree.expandAll(); //展開所有節點 //CatalogTtree.collapseAll(); //關閉所有節點 }); </script> </head>
treePanel展開所有,關閉所有
CatalogTtree.expandAll(); //展開所有節點 CatalogTtree.collapseAll(); //關閉所有節點
TreeGrid簡例,帶彈出window的form表單
程式碼:
Ext.onReady(function () { //獲取store var ClassTreeGridStore = Ext.create('Ext.data.TreeStore', { model: 'Task', proxy: { type: 'ajax', actionMethods: { create: "POST", read: "POST", update: "POST", destroy: "POST" }, url: '/queClass/GetClassTreeStore' }, fields: ["qcId", "claName", "pId", "lowScroe", "topScore"], folderSort: true }); //獲取tbar var tbar = Ext.create("Ext.toolbar.Toolbar", { items: [ { text: '新增兄弟分類', iconCls: 'a_add', handler: function () { AddDialog.setTitle("新增兄弟分類"); AddForm.form.reset(); Ext.getCmp("btnAdd").show(); Ext.getCmp("btnEdit").hide(); Ext.getCmp("pName").hide(); Ext.getCmp("bName").show(); if (typeof (ClassTreeGrid) == "undefined") { return false; } var rows = ClassTreeGrid.getView().getSelectionModel().getSelection(); if (typeof (rows[0]) == "undefined") { Ext.Msg.alert("提示", "請選擇要操作的行!"); return false; } Ext.getCmp("bName").setValue(rows[0].data.claName); AddDialog.show(); } }, '-', { text: '新增子分類', iconCls: 'a_add', handler: function () { AddDialog.setTitle("新增子分類"); AddForm.form.reset(); Ext.getCmp("btnAdd").show(); Ext.getCmp("btnEdit").hide(); Ext.getCmp("bName").hide(); Ext.getCmp("pName").show(); if (typeof (ClassTreeGrid) == "undefined") { return false; } var rows = ClassTreeGrid.getView().getSelectionModel().getSelection(); if (typeof (rows[0]) == "undefined") { Ext.Msg.alert("提示", "請選擇要操作的行!"); return false; } Ext.getCmp("pName").setValue(rows[0].data.claName); AddDialog.show(); } }, '-', { text: '刪除', iconCls: 'a_cross', handler: DelClass }, '-', { text: '修改', iconCls: 'a_edit', handler: function () { AddDialog.setTitle("修改分類"); AddForm.form.reset(); Ext.getCmp("btnEdit").show(); Ext.getCmp("btnAdd").hide(); Ext.getCmp("bName").hide(); Ext.getCmp("pName").hide(); if (typeof (ClassTreeGrid) == "undefined") { return false; } var rows = ClassTreeGrid.getView().getSelectionModel().getSelection(); if (typeof (rows[0]) == "undefined") { Ext.Msg.alert("提示", "請選擇要操作的行!"); return false; } AddForm.form.setValues(rows[0].data); AddDialog.show(); } }, '-', { text: "重新整理", iconCls: "a_refresh", handler: function () { //重新整理treepanel ClassTreeGridStore.load(); } }, '-', { text: '展開所有', iconCls: 'a_edit2', handler: function () { //展開所有函式 ClassTreeGrid.expandAll(); } }, '-', { text: '摺疊所有', iconCls: 'a_lock', handler: function () { //摺疊所有函式 ClassTreeGrid.collapseAll(); } } ] }); //treegrid var ClassTreeGrid = Ext.create('Ext.tree.Panel', { tbar: tbar, useArrows: true, rootVisible: false, store: ClassTreeGridStore, multiSelect: false, singleExpand: false, columns: [{ //定義tree的列 xtype: 'treecolumn', text: '分類名稱', //顯示的表頭列名稱 flex: 2, sortable: true, dataIndex: 'claName' //對應store的列欄位名稱 }, { text: '最小分值', flex: 1, dataIndex: 'lowScroe', sortable: true }, { text: '最大分值', flex: 1, dataIndex: 'topScore', sortable: true }] , listeners: { //點選行觸發事件 itemclick: function (record, node) { //把列的qcid傳遞給QuesGridStore重新整理對應的grid或tree QuesGridStore.load({ params: { csId: node.data.qcId } }); } } }); //彈出window的form表單 var AddForm = Ext.create("Ext.form.Panel", { border: false, fieldDefaults: { msgTarget: 'side', //提示資訊在右旁邊顯示圖示 labelWidth: 105, align: "right", regexText: '格式錯誤', //錯誤提示 allowBlank: false //不與許為空 }, defaults: { padding: 15, width: 380 }, defaultType: "textfield", items: [ { xtype: "hidden", name: 'pId', }, { fieldLabel: '父分類名稱', id: "pName", name: 'pName', disabled: true }, { fieldLabel: '兄弟分類名稱', id: "bName", name: 'bName', disabled: true }, { fieldLabel: '分類名稱', name: 'claName', }, { //表單中的數字控制元件 xtype: "numberfield", fieldLabel: '最小分值', name: 'lowScroe', regex: /^\d+$/, //正則驗證 maxLength: 100, }, { //表單中的數字控制元件 xtype: "numberfield", fieldLabel: '最大分值', regex: /^\d+$/, regexText: '格式錯誤', name: 'topScore', } ] }); //要彈出的window var AddDialog = Ext.create("Ext.window.Window", { iconCls: 'a_add', closeAction: 'hide', //視窗關閉的方式:hide/close resizable: false, closable: true, //是否可以關閉 modal: true, //是否為模態視窗 items: AddForm, buttons: [{ text: '新增', iconCls: 'a_add', id: "btnAdd", handler: function () { if (AddForm.form.isValid()) { if (AddDialog.title == '新增兄弟分類') { //O為兄弟分類,1為子分類 AddClass(0); } else { AddClass(1); } } } }, { text: '修改', iconCls: 'a_edit', //樣式 id: "btnEdit", handler: EditClass }, { id: "btnCancel", iconCls: 'a_cross', //樣式 text: '重置', handler: function () { //重置AddForm.form表單 AddForm.form.reset(); } }] }); new Ext.Viewport({ layout: "border", renderTo: Ext.getBody(), defaults: { bodyStyle: "background-color: #FFFFFF;", frame: true }, items: [{ region: "north", height: "60%", split: true, layout: "fit", border: true, items: [ClassTreeGrid] } ] }); //新增分類 function AddClass(type) { var rows = ClassTreeGrid.getView().getSelectionModel().getSelection(); var id = 0; var leaf = false; //兄弟分類 if (type == 0) { id = rows[0].data.pId; } else { id = rows[0].data.qcId; } Ext.Ajax.request({ method: "post", url: "/queClass/Add", params: { json: Ext.JSON.encode(AddForm.form.getValues()), id: id }, callback: function (options, success, response) { if (success) { var json = response.responseText; json = Ext.decode(json); ClassTreeGridStore.load(); Ext.Msg.alert("提示", json.msg); AddDialog.hide(); } else { Ext.Msg.alert("提示", "系統繁忙"); } } }); } //刪除分類 function DelClass() { var rows = ClassTreeGrid.getView().getSelectionModel().getSelection(); if (typeof (rows[0]) == "undefined") { Ext.Msg.alert("提示", "請選擇要操作的行!"); return false; } Ext.Ajax.request({ method: "post", url: "/queClass/Delete/", params: { qcId: rows[0].data.qcId }, callback: function (options, success, response) { if (success) { var json = response.responseText; json = Ext.decode(json); ClassTreeGridStore.load(); Ext.Msg.alert("提示", json.msg); AddDialog.hide(); } else { Ext.Msg.alert("提示", "系統繁忙"); } } }); } //修改分類 function EditClass() { var rows = ClassTreeGrid.getView().getSelectionModel().getSelection(); if (typeof (rows[0]) == "undefined") { Ext.Msg.alert("提示", "請選擇要操作的行!"); return false; } Ext.Ajax.request({ method: "post", url: "/queClass/Edit/", params: { json: Ext.JSON.encode(AddForm.form.getValues()), qcId: rows[0].data.qcId }, callback: function (options, success, response) { if (success) { var json = response.responseText; json = Ext.decode(json); ClassTreeGridStore.load(); Ext.Msg.alert("提示", json.msg); AddDialog.hide(); } else { Ext.Msg.alert("提示", "系統繁忙"); } } }); } });
treepanel右鍵選單編輯
程式碼:
//GUID function newGuid() { var guid = ""; for (var i = 1; i <= 32; i++) { var n = Math.floor(Math.random() * 16.0).toString(16); guid += n; if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) guid += "-"; } return guid; } //Toopitp Ext.tip.QuickTipManager.init(); //Model Ext.define('MyTreeModel', { extend: 'Ext.data.Model', fields: ['text','id','leaf','caitNo'] }); //Store Ext.define("MyTreeStore", { extend: "Ext.data.TreeStore", model: 'MyTreeModel', proxy: { type: 'ajax', api: { read: '/Tools/106.ashx?method=getCatalogItem', }, writer: { type: 'json', allowSingle: false, encode: true, root: 'records' } }, root: { id: -1, expanded: true, text: cataId, }, autoLoad: true }); var MyTreeStore = Ext.create("MyTreeStore"); Ext.define("MyTreePanel", { extend: 'Ext.tree.Panel', width: 250, height: 400, store: MyTreeStore, hideHeaders: true, rootVisible: true, viewConfig: { plugins: { ptype: 'treeviewdragdrop' }, listeners: { drop: function (node, data, dropRec, dropPosition) { store.sync(); } } }, initComponent: function () { var me = this; //可編輯 me.plugins = [me.cellEditingPlugin = Ext.create('Ext.grid.plugin.CellEditing')]; //定義列 me.columns = [{ xtype: 'treecolumn', dataIndex: 'text', flex: 1, editor: { xtype: 'textfield', selectOnFocus: true, validator: function (value) { value = Ext.String.trim(value); return value.length < 1 ? this.blankText : true; } } }, { xtype: 'actioncolumn', width: 24, icon: '/ExtUI/Image/a_delete.gif', iconCls: 'x-hidden', tooltip: '刪除', handler: Ext.bind(me.handleDeleteClick, me) }]; //定義選單 Ext.define('SimpleTasks.view.lists.ContextMenu', { extend: 'Ext.menu.Menu', xtype: 'listsContextMenu', items: [ { text: '兄弟節點', iconCls: 'a_add', id: 'new-list-item', handler: me.handleNewListClick, scope: me }, { text: '孩子節點', iconCls: 'a_add', id: 'new-folder-item', handler: me.handleNewFolderClick, scope: me }, { text: '刪除', iconCls: 'a_delete', id: 'delete-folder-item', }, { text: '重新整理', iconCls: 'a_refresh', id: 'refresh-folder-item', handler: function () { MyTreeStore.load({ params: grid.getView().getSelectionModel().getSelection()[0].data }); } } ] }); //定義底部tbar me.dockedItems = [{ xtype: 'toolbar', dock: 'bottom', items: [{ iconCls: 'a_add', tooltip: '兄弟節點', handler: me.handleNewListClick, scope: me }, { iconCls: 'a_add', tooltip: '孩子節點', handler: me.handleNewFolderClick, scope: me }, { iconCls: 'a_delete', id: 'delete-folder-btn', tooltip: '刪除', scope: me }, { iconCls: 'a_refresh', id: 'refesh-folder-btn', tooltip: '重新整理', handler: function () { MyTreeStore.load({ params: grid.getView().getSelectionModel().getSelection()[0].data }); } } ] }]; me.contextMenu = Ext.create("SimpleTasks.view.lists.ContextMenu"); me.callParent(); me.on("itemmouseenter", me.showActions); me.on("itemmouseleave", me.hideActions); me.on("edit", me.updateNode); me.on("afterrender", me.handleAfterListTreeRender); me.on("beforeedit", me.handleBeforeEdit, me); me.on("canceledit", me.handleCancelEdit); me.on("itemcontextmenu", me.showContextMenu, me); }, //重新整理樹 refreshView: function () { //refresh the data in the view. //This will trigger the column renderers to run, this.getView().refresh(); }, //顯示actioncolumn showActions: function (view, list, node, rowIndex, e) { var icons = Ext.DomQuery.select('.x-action-col-icon', node); if (view.getRecord(node).get('id') != "-1") { Ext.each(icons, function (icon) { Ext.get(icon).removeCls('x-hidden'); }); } }, //隱藏actioncolumn hideActions: function (view, list, node, rowIndex, e) { var icons = Ext.DomQuery.select('.x-action-col-icon', node); Ext.each(icons, function (icon) { Ext.get(icon).addCls('x-hidden'); }); }, //Handles a click on a delete icon handleDeleteClick: function (gridView, rowIndex, colIndex, column, e, record) { var thisNodes=this; Ext.Ajax.request({ url:"/Tools/106.ashx?method=deleteTreeNode&cataId="+cataId, params:record.data, callback:function(options,success,response){ if(success) { var responseJson=Ext.JSON.decode(response.responseText)[0]; if(responseJson.status=="true") { //這個model區別於普通的model //在定義store的時候並沒有定義fields或model屬性,該model由treeStore自動建立 //該model包含樹展示所需要的資料結構,具備parentNode,isLeaf,loaded等屬性 var model = gridView.getRecord(gridView.findTargetByEvent(e)); thisNodes.deleteNode(model); Ext.Msg.alert("提示",responseJson.msg); } else { Ext.Msg.alert("提示",responseJson.msg); } } else { Ext.Msg.alert("提示","請重新操作!"); } } }); }, //刪除節點 deleteNode: function (nodel) { nodel.parentNode.removeChild(nodel); //與伺服器端同步 MyTreeStore.sync(); }, //更新節點 updateNode: function (editor,e,node) { var me = this; // //與伺服器端同步 // MyTreeStore.sync(); if(e.record.data.id.length>8) { //插入 Ext.Ajax.request({ url:"/Tools/106.ashx?method=createTreeNode&cataId="+cataId, params:e.record.data, callback:function(options,success,response){ if(success) { var responJson=Ext.JSON.decode(response.responseText)[0]; if(responJson.status=="false") { Ext.Msg.alert("提示",responJson.msg); } else { MyTreeStore.load({ params: grid.getView().getSelectionModel().getSelection()[0].data }); } } else { Ext.Msg.alert("提示","系統繁忙"); } } }); } else { //更新 Ext.Ajax.request({ url:"/Tools/106.ashx?method=updateTreeNode&cataId="+cataId, params:e.record.data, callback:function(options,success,response){ if(success) { var responJson=Ext.JSON.decode(response.responseText)[0]; if(responJson.status=="false") { Ext.Msg.alert("提示",responJson.msg); } } else { Ext.Msg.alert("提示","系統繁忙"); } } }); } }, //樹載入完畢後設定預設選中第一個 handleAfterListTreeRender: function (tree) { tree.getSelectionModel().select(0); }, //編輯前判斷跟節點不允許編輯 handleBeforeEdit: function (editingPlugin, e) { return e.record.get('id') !== -1; }, //取消編輯事件 handleCancelEdit: function (editor, e) { var list = e.record, parent = list.parentNode; parent.removeChild(list); this.getListTree().getSelectionModel().select([parent]); }, //新增葉子節點 handleNewListClick: function (component, e) { this.addNode(true); }, //新增跟節點 handleNewFolderClick: function (component, e) { this.addNode(); }, //新增節點 addNode: function (leaf) { var me = this; var listTree = me; cellEditingPlugin = listTree.cellEditingPlugin, selectionModel = listTree.getSelectionModel(), selectedList = selectionModel.getSelection()[0], parentList = leaf?selectedList.parentNode : selectedList, newList = Ext.create('MyTreeModel', { id: newGuid(), text: 'New List', leaf: true, loaded: true }), expandAndEdit = function () { if (parentList.isExpanded()) { selectionModel.select(newList); cellEditingPlugin.startEdit(newList, 0); } else { listTree.on('afteritemexpand', function startEdit(list) { if (list === parentList) { selectionModel.select(newList); cellEditingPlugin.startEdit(newList, 0); // remove the afterexpand event listener listTree.un('afteritemexpand', startEdit); } }); parentList.expand(); } }; //判斷是否是子節點 if(selectedList.isLeaf()) { if(!leaf) //判斷是新增子節點還是兄弟節點 { MyTreeStore.getNodeById(selectedList.data.id).set('leaf', false); } } parentList.appendChild(newList); if (listTree.getView().isVisible(true)) { expandAndEdit(); } else { listTree.on('expand', function onExpand() { expandAndEdit(); listTree.un('expand', onExpand); }); listTree.expand(); } }, //新增右鍵選單 showContextMenu: function (view, list, node, rowIndex, e) { this.contextMenu.showAt(e.getX(), e.getY()); e.preventDefault(); } }); //編輯樹Window var EditTreeWindow=Ext.create("Ext.window.Window",{ title: '編輯樹', iconCls:'a_edit', closeAction: 'hide', //視窗關閉的方式:hide/close resizable: false, closable: true, //是否可以關閉 modal: true, //是否為模態視窗 items: Ext.create("MyTreePanel") });
這一篇,我都只是檢視,然後程式碼,如果多有疑問,歡迎你加入左上角的群,我們們一起努力,進步。