<html>
<script language=Javascript>
TreeNode = function(name, data, parentNode)
{
this.name = name;
this.parentNode = parentNode;
this.data = data;
this.childNodes = [];
this.addChildNode = function(node)
{
node.parentNode = this;
this.childNodes.push(node);
return this;
}
this.fullSelected = function()
{
for(var index in this.childNodes)
{
if(!this.childNodes[index].data.checked)
{
return;
}
}
this.data.checked = true;
if(this.parentNode){
this.parentNode.fullSelected();
}
}
this.select = function()
{
this.data.checked = true;
for(var index in this.childNodes)
{
this.childNodes[index].select();
}
if(this.parentNode)
{
this.parentNode.fullSelected();
}
}
this.cancel = function()
{
this.data.checked = false;
if(this.parentNode)
{
this.parentNode.cancel();
}
}
this.cancel2 = function()
{
this.data.checked = false;
for(var index in this.childNodes)
{
this.childNodes[index].cancel2();
}
}
this.init = function()
{
var instance = this;
instance.data.instanceNode = this;
instance.data.onclick = function()
{
if(this.checked == true)
{
this.instanceNode.select();
}
else
{
this.instanceNode.cancel();
this.instanceNode.cancel2();
}
}
}
this.each = function(itFun)
{
itFun(this);
for(var index in this.childNodes)
{
this.childNodes[index].each(itFun);
}
}
this.init();
}
function $(id)
{
return document.getElementById(id);
}
var allx = null;
function main()
{
allx = new TreeNode("all", $('all'));
var a = new TreeNode("a", $('a'));
var a1 = new TreeNode("a1", $('a1'));
var a2 = new TreeNode("a2", $('a2'));
var a3 = new TreeNode("a3", $('a3'));
a.addChildNode(a1).addChildNode(a2).addChildNode(a3);
var b = new TreeNode("b", $('b'));
var b1 = new TreeNode("b1", $('b1'));
var b2 = new TreeNode("b2", $('b2'));
var b3 = new TreeNode("b3", $('b3'));
b.addChildNode(b1).addChildNode(b2).addChildNode(b3);
var c = new TreeNode("c", $('c'));
var c1 = new TreeNode("c1", $('c1'));
var c2 = new TreeNode("c2", $('c2'));
var c3 = new TreeNode("c3", $('c3'));
c.addChildNode(c1).addChildNode(c2).addChildNode(c3);
allx.addChildNode(a).addChildNode(b).addChildNode(c);
}
/** 获得叶子节点的值,以数组返回 */
function getValues(treeNode){
var values = [];
var itFun = function(node)
{
if(!node.childNodes || node.childNodes.length == 0)
{
if(node.data.checked){
values.push(node.data.value);
}
}
}
treeNode.each(itFun);
return values;
}
</script>
<body οnlοad="main()">
ALL<input type=checkbox id="all" ><br><br><br>
A<input type=checkbox id="a" ><br>
<input type=checkbox id="a1" value="1"><input type=checkbox id="a2" value="2"><input type=checkbox id="a3" value="3"><br><br>
B<input type=checkbox id="b" ><br>
<input type=checkbox id="b1" value="4"><input type=checkbox id="b2" value="5"><input type=checkbox id="b3" value="6"><br><br>
C<input type=checkbox id="c" ><br>
<input type=checkbox id="c1" value="7"><input type=checkbox id="c2" value="8"><input type=checkbox id="c3" value="9"><br><br>
<input type="button" value="getValues" οnclick="alert(getValues(allx))"/>
</body>
<html>