带复选框(checkbox)的树

官方实例中有介绍如何将json数据变成一棵树的简单例子
该例子可以满足我们的一般需求。很多时候我们需要用到带checkbox的树。
其实加个checkbox框先简单,只需要在返回来的json数据中加上 checked 项(为true/false)。要实现我们想要的选中父节点的checkbox后,自动选中子节点也很简单,只需要加上下面这一段代码就可以了。

tree.on('checkchange', function(node, checked) {   
		node.expand();   
		node.attributes.checked = checked;   
		node.eachChild(function(child) {   
			child.ui.toggleCheck(checked);   
			child.attributes.checked = checked;   
			child.fireEvent('checkchange', child, checked);   
		});   
	}, tree); 

演示(demo)地址在文章最后.

效果图如下:

源代码包括 0005_checkbox_reorder.html,0005_checkbox_reorder_tree.php.

0005_checkbox_reorder.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>带复选框(checkbox)的树</title>
<link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />
<script type="text/javascript" src="../../adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../ext-all.js"></script>
<link rel="stylesheet" type="text/css" href="../../examples/examples.css" />
<script type="text/javascript" src="../../examples.js"></script>
<script type="text/javascript">
Ext.onReady(function(){
	Ext.BLANK_IMAGE_URL = "../../resources/images/default/s.gif"  	
    // shorthand
    var Tree = Ext.tree;
    
    var tree = new Tree.TreePanel({
        el:'tree-div',
        useArrows:true,
        autoScroll:true,
        animate:true,
        enableDD:true,
        containerScroll: true, 
        loader: new Tree.TreeLoader({
            dataUrl:'0005_checkbox_reorder_tree.php'
        })
    });
	
	tree.on('checkchange', function(node, checked) {   
		node.expand();   
		node.attributes.checked = checked;   
		node.eachChild(function(child) {   
			child.ui.toggleCheck(checked);   
			child.attributes.checked = checked;   
			child.fireEvent('checkchange', child, checked);   
		});   
	}, tree);  

    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: 'Ext JS',
        draggable:false,
        id:'source'
    });
    tree.setRootNode(root);

    // render the tree
    tree.render();
    root.expand();
});
</script>

</head>
<body>
<h1>带复选框(checkbox)的树</h1>
<p></p>
<p>改编自ExtJs 自带的tree例子,选中父节点后,所有子节点会自动选上。</p>

<p>该例子点击父节点如果速度过快,有时候不会自动选中子节点! </p>

<div id="tree-div" style="overflow:auto; height:300px;width:250px;border:1px solid #c3daf9;"></div>

</body>
</html>

0005_checkbox_reorder_tree.php

[{"cls":"folder","id":10,"leaf":false,checked:false,"children":[{"cls":"file","id":11,"leaf":true,checked:false,"children":null,"text":"S600"},{"cls":"file","id":12,"leaf":true,checked:false,"children":null,"text":"SLK200"}],"text":"Benz"}]

演示地址:http://extjs.org.cn/extjs/mydemo/tree/0005_checkbox_reorder.html

(版权声明:本篇文章版权属于extjs.org.cn所有,可以在互联网上进行转载,转载必须保留作者版权声明及链接;也可以文章用于出版、发行或其它商业用途,仅仅需要保留作者版权声明及链接。)

评论

如何将选中的结果再传给后台呢??

非常好,帮我解决了大问题,可是如何将选中的结果再传给后台呢??

应该是遍历树,或者用数组记录下

应该是遍历树,或者用数组记录下