你如何在javascript中定位父母和孩子<ul>?</ul>

时间:2012-12-30 16:23:32

标签: javascript menu

只是一个快速的,但我在解决它时遇到了一些麻烦。

我正在使用javascript来检测菜单中的元素:

var nav = document.getElementById('nav');
var list = nav.children.length;

但是菜单已嵌套<ul>下拉列表,我该如何定位这些?

2 个答案:

答案 0 :(得分:0)

nav.getElementsByTagName('ul')会在<ul>内为您提供所有nav个元素。

对于DOM中的更复杂搜索,您可以使用querySelector/querySelectorAllselect elements的方式将CSS样式应用于'#id ul''.someClass'等。 )。

答案 1 :(得分:0)

在查看你的代码并实际阅读和看到你的小提琴后,我删除了我的另一个答案,因为它误解了你的需要......

简而言之,你需要编写一个递归函数来遍历所有的子uls。我没有运行我的开发环境,所以psuedo会为你编写代码(我相信你会得到漂移)

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
    }
    }
}

这是小提琴形式的完整递归函数

Working fiddle

CODE

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;
    }
}
}