<script type="text/javascript">
Ext.onReady(function(){
var tree= new Ext.tree.TreePanel({
el:'tree',
loader:new Ext.tree.TreeLoader()
});
var root = new Ext.tree.AsyncTreeNode({
text:'我是根',
children:[{
text:'01',qtip:'我是鼠标提示',//如果有qtip属性,则必须要有Ext.QuickTips.init()这句话
children:[{
text:'01-01',
leaf:true //这里为true代表他下面已经没有子节点,不需要加载出来
},{
text:'01-02',
children:[{
text:'01-02-01',
leaf:true
},{
text:'01-02-02',
leaf:true
}]
},{
text:'01-03',
leaf:true,
href:"http://www.baidu.com",//通过点击节点,可以链接到一个地址
hrefTarget:'_blank'
}]
},
{
text:'02',
leaf:true,
icon:'user_female.png' //自定义节点的图标
}]
});
tree.setRootNode(root);
tree.render();
tree.on('dblclick',function(node){
Ext.Msg.alert('您刚刚双击了',node.text);
});
//右键菜单
var contextmenu = new Ext.menu.Menu({
id:'thecontextmenu',
items:[{
text:'选择',
handler: function() {
alert('你选择的是=' + tree.getSelectionModel().getSelectedNode().text + " 结点");
}
}]
});
//右键菜单显示
tree.on('contextmenu',function(node,e){
e.preventDefault();//防止浏览器弹出默认的右键菜单
node.select();//节点进入选中状态
contextmenu.showAt(e.getXY());
});
tree.on('click',function(node){
Ext.Msg.show({
title:'提示',
msg:'您点击了:'+node,
animEl:node.ui.textNode
});
});
root.expand();
Ext.QuickTips.init(); //初始化接点提示
tree.expandAll();//展开所有节点
});
</script>
注:body中应该有个<div id='tree'></div>,最好给其设置合适的高度,用来显示tree。
上面节点都是写死的。今天搞了下动态加载的,其实也不难,只是在dataUrl上写上你要提交到得url即可。
<script type="text/javascript">
Ext.onReady(function(){
var tree= new Ext.tree.TreePanel({
el:'tree',
loader:new Ext.tree.TreeLoader({dataUrl:'GetTreeServlet'})//'GetTreeServlet'是我在后台的servlet的名字
});
var root = new Ext.tree.AsyncTreeNode({text:'偶是根'});
tree.setRootNode(root);
root.expand();
tree.render();
//tree.expandAll();//展开所有节点
});
</script>
后台的java代码:
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
StringBuffer buffer = new StringBuffer();
/***
* 返回的内容要是这样:
* [
* {text:'根节点一',children:[
* {text:'根节点一一',leaf:true},
* {text:'根节点一二',leaf:true}
* ]},
* {text:'根节点二',leaf:true}
* ]
* **/
buffer.append("[");
buffer.append("{");
buffer.append("text:'根节点一',");
buffer.append("children:");
buffer.append("[");
buffer.append("{");
buffer.append("text:'根节点一一',leaf:true");
buffer.append("},");
buffer.append("{");
buffer.append("text:'根节点一二',leaf:true");
buffer.append("}");
buffer.append("]");
buffer.append("},");
buffer.append("{");
buffer.append("text:'根节点二',");
buffer.append("leaf:true");
buffer.append("}");
buffer.append("]");
response.getWriter().print(buffer.toString());
记得设定编码方式为"UTF-8"。页面效果如图