转自:http://blog.csdn.net/net_lover/article/details/6702027
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>无标题页</title> <script type="text/javascript"> var nextInput = null; var nextID = null; var preInput = null; var preID = null; var uncheckParent = false; var pId; function checkIt(o) { preInput = nextInput = o.checked; nextID = o.id; preID = o.getAttribute("parentId"); uncheckParent = false; checkStart(o) } function checkStart(o) { checkChild(o) checkParent(o) } function checkChild(o) { obj = o; if (obj.nodeType == 1 && obj.tagName == "INPUT" && obj.type == "checkbox") { if (obj.getAttribute("id").substr(0, nextID.length) == nextID) obj.checked = nextInput } obj = obj.nextSibling; if (obj == null) return; checkChild(obj); } function checkParent(o) { pId = o.getAttribute("parentId"); obj = o.previousSibling; while (obj && obj.nodeType != 1 && obj.tagName != "INPUT" && obj.type != "checkbox") { obj = obj.previousSibling; if (obj == null) return; } if (obj == null) return; if (obj.getAttribute("id") == preID) { preID = obj.getAttribute("parentId"); obj.checked = preInput if (uncheckParent) obj.checked = false; } //判断是否要取消父节点选择 chs = document.getElementById("tree").getElementsByTagName("INPUT"); for (i = 0; i < chs.length; i++) { if (chs[i].getAttribute("parentId") == pId) { if (chs[i].checked == false) { uncheckParent = true; break; } } } checkParent(obj); } </script> </head> <body> <form id="form1" runat="server"> <div id="tree"> <input type="checkbox" id="1" onclick="checkIt(this)" parentid="0" />1<br /> <input type="checkbox" id="11" onclick="checkIt(this)" parentid="1" />11<br /> <input type="checkbox" id="12" onclick="checkIt(this)" parentid="1" />12<br /> <input type="checkbox" id="121" onclick="checkIt(this)" parentid="12" />121<br /> <input type="checkbox" id="122" onclick="checkIt(this)" parentid="12" />122<br /> <input type="checkbox" id="13" onclick="checkIt(this)" parentid="1" />13<br /> <input type="checkbox" id="131" onclick="checkIt(this)" parentid="13" />131<br /> <input type="checkbox" id="132" onclick="checkIt(this)" parentid="13" />132<br /> <input type="checkbox" id="2" onclick="checkIt(this)" parentid="0" />2<br /> <input type="checkbox" id="21" onclick="checkIt(this)" parentid="2" />21<br /> <input type="checkbox" id="3" onclick="checkIt(this)" parentid="0" />3<br /> </div> </form> </body> </html>