function initMenu() {
assembleMenu(document.getElementById("navigation"));
}
function assembleMenu(uLParentNode) {
var theUL = uLParentNode.getElementsByTagName("ul")[0]; //在取得id为navigation的元素后,通过getElementsByTagName("ul")取得其下所有的UL元素。该函数所返回的列表包含了所有嵌套的多级的UL元素,但我们只关心第一个,因此,通过下标访问符[0]返回第一个UL元素,并存放于theUL变量中。
var theULChilds = theUL.childNodes; //取得theUL的所有子节点。在DOM2中,childNodes是节点是一个属性,它返回相应对象的下一级的所有子节点。与getElementsByTagName不同的地方是,它只返回紧邻下一级的所有子节点。
for (var i=0; i<theULChilds.length; i++) { //开始遍历所返回的子节点。
if (theULChilds[i].tagName == "LI") { //我们只关心LI节点,因此,对于不同浏览器的返回结果,此行可统一地过滤掉其他类型的子节点。
var theLINode = theULChilds[i];
if (hasNextLevelMenu(theLINode)) {
setMouseActions(theLINode);
theLINode.firstChild.className = uLParentNode.tagName == "DIV" ? "downMenu" : "rightMenu";
assembleMenu(theLINode); //如果有下级菜单,则将LI节点下第一个子节点的className属性设为downMenu。而LI节点的第一个子节点正好是A标签:
}
}
}
function hasNextLevelMenu(node) {
return node.getElementsByTagName("ul").length > 0;
}
function setMouseActions(node) {
node.onmouseover = function() {
this.getElementsByTagName("ul")[0].style.display = "block";
this.firstChild.style.backgroundColor= "#FFF";
};
node.onmouseout = function() {
this.getElementsByTagName("ul")[0].style.display = "none";
this.firstChild.style.backgroundColor= "#EEE";
};
}
}