首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在javascript中定位父<ul>和子you?

如何在javascript中定位父<ul>和子you?
EN

Stack Overflow用户
提问于 2012-12-31 00:23:32
回答 2查看 154关注 0票数 0

只是一个很快的问题,但我有点想不通了。

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

代码语言:javascript
代码运行次数:0
运行
复制
var nav = document.getElementById('nav');
var list = nav.children.length;

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-31 01:11:31

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

简而言之,您需要编写一个递归函数来遍历找到的所有子uls。我没有运行我的开发环境,所以我将为你做这个代码(我相信你会明白的)

代码语言:javascript
代码运行次数:0
运行
复制
RecursiveFunction(document.getElementById('nav'), "-");

//其他地方

代码语言:javascript
代码运行次数:0
运行
复制
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

代码

代码语言:javascript
代码运行次数:0
运行
复制
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;
    }
}
}
票数 0
EN

Stack Overflow用户

发布于 2012-12-31 00:30:13

nav.getElementsByTagName('ul')将为您提供nav中的所有<ul>元素。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14092333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档