給 ASP.NET 的 TreeView 寫了一個掛件,主要功能就是在 TreeView 是 ShowCheckBox 模式的時候,當勾選某個節點時能自動的勾選這個節點相關的所有父節點,以及勾選、反勾選這個節點的所有子節點。
功能很簡單純 javascript 實現:
/*************************************************************************
* change the tree view node's child nodes check-state, when check
* this node.
*
* NOTE: for ASP.NET TreeView
*
* @author h_Davy
* @version 2008-12-5
*************************************************************************/
/**
* check the tree node's childs with this checkbox's stats
*
* @param chk the check box element
*
* @private
*/
function _checkTreeChilds(chk)
{
var childId = chk.id.replace('CheckBox', 'Nodes');
var child = document.getElementById(childId);
if (child) {
var chks = child.getElementsByTagName('input');
for (var i in chks) {
if (chks[i].type == "checkbox") {
chks[i].checked = chk.checked;
}
}
}
}
/**
* find out the checkbox-node's parent node's checkbox id
*
* @param chk the check box element
* @param treeView the treeView element
*
* @return the parent node checkbox id
*
* @private
*/
function _findTreeParentId(chk, treeView)
{
if (!chk) return null;
var tmpElm = chk.parentNode;
for(;;) {
if (tmpElm.tagName == "TABLE") {
return tmpElm.parentNode.id.replace('Nodes', 'CheckBox');
} else {
// go up to find out the parent node, until touch the treeview
tmpElm = tmpElm.parentNode;
if (tmpElm == treeView) return null;
}
}
return null;
}
/**
* check the tree node's parent w this checkbox is checked
*
* @param chk the check box element
* @param treeView the treeView element
*
* @private
*/
function _checkTreeParent(chk, treeView)
{
if (!chk.checked) return;
var tmpChk;
var parentId = _findTreeParentId(chk);
for(;;) {
if (!parentId) return;
if (chk.checked) {
tmpChk = document.getElementById(parentId);
if (!tmpChk || tmpChk == treeView) return;
tmpChk.checked = true;
}
parentId = _findTreeParentId(tmpChk, treeView);
}
}
/**
* use this bind to a tree view
*
* @param id the tree view's id (NOTE: it's the HTML node id, not .NET page server id)
*/
function bindCheckEvent(id) {
var treeView = document.getElementById(id);
var chks = treeView.getElementsByTagName('input');
for(var i in chks) {
if (chks[i].type == "checkbox") {
chks[i].onclick = function() {
_checkTreeChilds(this);
_checkTreeParent(this, treeView);
};
}
}
}
// -- EOF --
使用方法,在要使用的頁面導入以上代碼后,在頁面結尾處加上:
<script type="text/javascript">
bindCheckEvent('TreeView1');
// 這里的 'TreeView1' 就是那個TreeView的ID
// !!!注意:這里的ID指的是最終生成的HTML頁面中的ID,
// 如果你的TreeView是在某個使用了模板頁的內容頁里面的話,
// 就有可能是 'ctl00_ContentPlaceHolder1_TreeView1' 了。
</script>
//EOF

1 comments:
最终生成的ID,可以在服务端代码中用 ClientID 得到。
Post a Comment