js实现点中子节点父节点自动选中
<script type="text/javascript" language="javascript">
function setParentState(objNode) {
var objParentDiv = WebForm_GetParentByTagName(objNode, "div");
if (objParentDiv == null || objParentDiv == "undefined")
return;
var divID = objParentDiv.getAttribute("ID");
var prefix = divID.substring(0, divID.indexOf("Nodes"));
var parentID = prefix + "CheckBox";
var parentChk = document.getElementById(parentID);
if (parentChk == null || parentChk == "undefined")
return;
if (objNode.checked) {
parentChk.checked = true;
}
else {
if (isAllChildrenUnChecked(parentChk)) {
parentChk.checked = false;
}
}
setParentState(parentChk);
}
function setChildState(objNode)//设定子控件状态
{
var nodeID = objNode.getAttribute("ID"); //chkBox ID
var prefix = nodeID.substring(0, nodeID.indexOf("CheckBox")); //节点的前缀
var childrenDiv = document.getElementById(prefix + "Nodes");
if (childrenDiv == null || childrenDiv == "undefined")
return;
var childrenArray = childrenDiv.children; //取得所有子控件
for (var i = 0; i < childrenArray.length; i++) {
var container = childrenArray[i]; //子控件的容器
var chk = WebForm_GetElementByTagName(container, "input"); //查找Check控件,由于只有一个种Input控件,就是CheckBox
chk.checked = objNode.checked;
setChildState(chk);
}
}
function isAllChildrenUnChecked(objChk) {
var objChkID = objChk.getAttribute("ID");
var prefix = objChkID.substring(0, objChkID.indexOf("CheckBox")); //节点的前缀
var childrenDiv = document.getElementById(prefix + "Nodes");
if (childrenDiv == null || childrenDiv == "undefined")
return;
var childrenArray = childrenDiv.children; //取得所有子控件
for (var i = 0; i < childrenArray.length; i++) {
var container = childrenArray[i]; //子控件的容器
var chk = WebForm_GetElementByTagName(container, "input"); //查找Check控件,由于只有一个种Input控件,就是CheckBox
if (chk.checked)
return false;
}
return true;
}
//触发事件
function HandleCheckEvent() {
var objNode = event.srcElement;
if (objNode.tagName != "INPUT" || objNode.type != "checkbox")
return;
//设定子Chk状态
setChildState(objNode);
//设定父Chk状态
setParentState(objNode);
}
</script>