只是一个快速的,但我很难理解它。
我正在使用 javascript 来检测菜单中的元素:
var nav = document.getElementById('nav');
var list = nav.children.length;
但是菜单已经嵌套<ul>
了下拉菜单,我该如何定位这些?
只是一个快速的,但我很难理解它。
我正在使用 javascript 来检测菜单中的元素:
var nav = document.getElementById('nav');
var list = nav.children.length;
但是菜单已经嵌套<ul>
了下拉菜单,我该如何定位这些?
nav.getElementsByTagName('ul')
会给你<ul>
里面的所有元素nav
。
对于 DOM 中更复杂的搜索,您可以使用将 CSS 样式应用于元素的方式querySelector/querySelectorAll
来选择元素'#id ul'
( 、'.someClass'
等)。
在查看您的代码并实际阅读并看到您的小提琴后,我删除了我的其他答案,因为它误解了您的需求......
简而言之,您需要编写一个递归函数以在找到时遍历所有子ul。我没有运行我的开发环境,所以会为你编写这个伪代码(我相信你会明白的)
RecursiveFunction(document.getElementById('nav'), "-");
//别处
function RecursiveFunction(domElement, prependedChar)
{
//because this is .js you will probably need some closures...
var currPrependedChar = prependedChar;
var dom = domElement;
//iterate all nodes, check if they are a li/a and populate dropdown...
for(count;count < dom.list.Length;++count){
//if the element you have found is a ul recurse
if(dom.list[count] == "ul"){
RecursiveFunction(dom.list[count], currPrependedChar + currPrependedChar ); //this calls this function
}else{
//combobox option.Value = currPrependedChar + elementInnerText
}
}
}
这是小提琴形式的完整递归函数
代码
function RecursiveFunction(currDom, currPrependedChar) {
//because this is .js you will probably need some closures...
var prependedChar = currPrependedChar;
var dom = currDom;
var children = dom.children;
var childrenCount = children.length;
//iterate all nodes, check if they are a li/a and populate dropdown...
for (var i = 0; i < childrenCount; ++i) {
var curElem = children[i];
//if the element you have found is a ul recurse
switch (curElem.nodeName) {
case "A":
var option = document.createElement('option');
option.innerHTML = prependedChar + curElem.text;
option.value = curElem.href;
select.appendChild(option);
break;
default:
if(curElem.nodeName == "UL") prependedChar += prependedChar
RecursiveFunction(curElem, prependedChar);
break;
}
}
}