项目中用到了树形菜单,但看代码后,发现有些属性怪怪的,有和没有,页面显示的结果是一样的,为了搞清楚如果弄树形菜单,Ricki自己依样画葫芦,仿造了一个,过程中确实学到不少,所以说,看还不如动手更能掌握,代码如下:
Ext.onReady(function(){ Ext.QuickTips.init(); var tabPanel = new Ext.TabPanel({ region: 'center' }); var menuTree = new Ext.tree.TreePanel({ useArrows:true, region: 'west',//指定布局 animate:true, collapsible: true, rootVisible:false,//不显示根节点 width:200, root:new Ext.tree.AsyncTreeNode({//用Ext.tree.TreeNode不行 id:'menuRoot', text:'menuRoot' }), dataUrl:'/MenuAction!loadTree.action', listeners:{ 'click':function(node,e){ var randomnumber=Math.floor(Math.random()*100000);//作为地址的传递参数 以使每次访问时重新获取数据 而非缓存中信息 var tab = Ext.get('tab_'+node.id); e.stopEvent();//停止事件传递 否则会促使浏览器发送URL(菜单链接)向服务器发送请求 if(node.leaf){ if(tab == null){ alert(node.attributes.href); var subTabPanel = new Ext.Panel({ id:'tab_'+node.id, title:node.text, closable:true, html:'<iframe id="iframe_'+node.id+'" name="iframe_'+node.id+'" scrolling="auto" frameborder="0" width="100%" height="100%" src="'+node.attributes.href+"?random="+randomnumber+'"></iframe>' }); tabPanel.add(subTabPanel);//添加该panel tabPanel.setActiveTab('tab_'+node.id);//激活它 }else{ tabPanel.setActiveTab("tab_"+node.id);//如果已经存在 则激活它 } } } } }); var viewPort = new Ext.Viewport({ layout:'border', items:[menuTree,tabPanel]//放进去才开始加载菜单项 }); });
PS:需要注意的问题
1.必须在TreePanel中设置root,否则将报'this.root'为空或不是对象
2.如果在TreePanel中设置region的值,那么Viewport的layout须为border。如:
region : String
Note: this config is only used when this BoxComponent is rendered by a Container which has been configured to use the BorderLayout layout manager (e.g. specifying layout:'border').
3.只设置TreePanel的region的值还不够,还必须设置TabPanel的region值,否则将报:
uncaught exception: No center region defined in BorderLayout ext-comp-1004
4.A TreeLoader provides for lazy loading of an Ext.tree.TreeNode's child nodes from a specified URL. The response must be a JavaScript Array definition whose elements are node definition objects.e.g.:
[{
id: 1,
text: 'A leaf Node',
leaf: true
},{
id: 2,
text: 'A folder Node',
children: [{
id: 3,
text: 'A child Node',
leaf: true
}]
}]
根据这个,只需在server端返回一个节点数组即可。
其中每个节点差不多如下定义:
public class Note{
private int id;
private String text;
private String href;
private boolean leaf;//true if this node is a leaf and does not have children
private ArrayList<Note> Notes;//存放子菜单
......
}
5.当rootVisible为true时,则根节点将显示(这个看自己的情况而定)
6.如果想实现有复选框的树形菜单,那么只需在上面的Note对象中添加boolean checked属性即可。
有空的话,欢迎到红番薯逛逛