只是一个很快的问题,但我有点想不通了。
我正在使用javascript来检测菜单中的元素:
var nav = document.getElementById('nav');
var list = nav.children.length;
但是菜单中嵌套了下拉列表的<ul>
,我该如何定位这些呢?
发布于 2012-12-30 17:11:31
在看了你的代码和实际阅读并看到你的小提琴后,我删除了我的另一个答案,因为它曲解了你需要的东西……
简而言之,您需要编写一个递归函数来遍历找到的所有子uls。我没有运行我的开发环境,所以我将为你做这个代码(我相信你会明白的)
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;
}
}
}
发布于 2012-12-30 16:30:13
nav.getElementsByTagName('ul')
将为您提供nav
中的所有<ul>
元素。
对于DOM中更复杂的搜索,您可以按照应用querySelector/querySelectorAll
样式的方式使用select elements ('#id ul'
、'.someClass'
等)。
https://stackoverflow.com/questions/14092333
复制