Javascript - 遍历元素的递归函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18004547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:25:39  来源:igfitidea点击:

Javascript - Recursive function to iterate through elements

javascriptjqueryrecursioniteration

提问by dudemanbearpig

I've just started reading up on JavaScript and I'm trying to write a small recursive function that would search through given nodes and return a list of values as a string.

我刚刚开始阅读 JavaScript,我正在尝试编写一个小的递归函数,该函数将搜索给定的节点并将值列表作为字符串返回。

My HTML structure could be something like

我的 HTML 结构可能类似于

<div id="parentfolder">parentfolder1
    <div class ="item1">item1</div>
    <div class ="item2">item2</div>
    <div id="parentfolder">parentfolder2
        <div class ="item1">item1</div>
        <div class ="item2">item2</div>
    </div>
</div>

And Here is my Javascript function:

这是我的 Javascript 函数:

function jsoncreator(parentfolderclass){
    var jstring = '';

    //get first occurance of parent folder
    var parentfolder = document.getElementById(parentfolderclass);
    var childnodes = parentfolder.childNodes;

    for (property in childnodes){
        jstring += property+ childnodes[property];
        if(childnodes[property] === parentfolderclass){
            jsoncreator(parentfolderclass);
            jstring += childnodes[property].value + '<br>';
        }
        else{
            //jstring += childnodes[i].value + '<br>';
        }
    }
    document.write(jstring);
}

All im getting back is

我回来的只是

0[object Text]1[object HTMLDivElement]2[object Text]3[object HTMLDivElement]4[object Text]5[object HTMLDivElement]6[object Text]length7itemfunction item() { [native code] }

When I try to print the childnodes values, I get a bunch of undefined returns.

当我尝试打印 childnodes 值时,我得到了一堆未定义的返回值。

If anybody could explain what I'm doing wrong, I'd really appreciate it.

如果有人能解释我做错了什么,我将不胜感激。

回答by Xotic750

You will need to do something like the following (recursive cross-browser)

您将需要执行以下操作(递归跨浏览器)

Javascript

Javascript

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

function textNodeValuesToArray(node) {
    if (typeof node === "string") {
        node = document.getElementById(node);
    }

    var arrayOfText = [];

    function pushText(currentNode) {
        if (currentNode.nodeType === 3) {
            arrayOfText.push(currentNode.nodeValue);
        }
    }

    walkTheDOM(node, pushText);

    return arrayOfText;
}

console.log(textNodeValuesToArray("parentfolder"));

On jsfiddle

jsfiddle 上

Or using treewalker

或使用 treewalker

Browser compatibility

Supported by IE9+, FF2+, Chrome 1+, Safari 3+, Opera 9+

浏览器兼容性

支持 IE9+, FF2+, Chrome 1+, Safari 3+, Opera 9+

Javascript

Javascript

function textNodeValuesToArray(node) {
    if (typeof node === "string") {
        node = document.getElementById(node);
    }

    var arrayOfText = [],
        treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, {
            acceptNode: function (node) {
                return NodeFilter.FILTER_ACCEPT;
            }
        }, false);

    while (treeWalker.nextNode()) {
        arrayOfText.push(treeWalker.currentNode.nodeValue);
    }

    return arrayOfText;
}

console.log(textNodeValuesToArray("parentfolder"));

On jsfiddle

jsfiddle 上

Without recursion and cross browser would be something like this

没有递归和跨浏览器会是这样的

Javascript

Javascript

Avoid using labels

Labels are not very commonly used in JavaScript since they make programs harder to read and understand. As much as possible, avoid using labels and, depending on the cases, prefer calling functions or throwing an error.

避免使用标签

标签在 JavaScript 中不是很常用,因为它们使程序更难阅读和理解。尽可能避免使用标签,并根据情况选择调用函数或抛出错误。

function walkDOM(root, func) {
    var node = root;

    start: while (node) {
        func(node);
        if (node.firstChild) {
            node = node.firstChild;
            continue start;
        }

        while (node) {
            if (node === root) {
                break start;
            }

            if (node.nextSibling) {
                node = node.nextSibling;
                continue start;
            }

            node = node.parentNode;
        }
    }
}

function textNodeValuesToArray(node) {
    if (typeof node === "string") {
        node = document.getElementById(node);
    }

    var arrayOfText = [];

    function pushText(currentNode) {
        if (currentNode.nodeType === 3) {
            arrayOfText.push(currentNode.nodeValue);
        }
    }

    walkDOM(node, pushText);

    return arrayOfText;
}

console.log(textNodeValuesToArray("parentfolder"));

On jsfiddle

jsfiddle 上

回答by Shylo Hana

<div id="parentfolder">parentfolder1
  <div class ="item1">item1</div>
  <div class ="item2">item2</div>
  <div class="subfolder">parentfolder2
    <div class ="item1">item1</div>
    <div class ="item2">item2</div>
  </div>
</div>



var children = document.getElementById('parentfolder').getElementsByClassName('*');
var childValues = new Array();

for(i=0; i<children.length; i++) {
  if(children[i].className == 'subfolder') {
    continue;
  } else {
    childValues.push(children[i].innerHTML);
  }
}