Javascript 我如何使这个循环所有孩子递归?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2712136/
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-08-23 01:35:22  来源:igfitidea点击:

How do I make this loop all children recursively?

javascriptrecursionloopsfor-loopchildren

提问by Matrym

I have the following:

我有以下几点:

for (var i = 0; i < children.length; i++){
   if(hasClass(children[i], "lbExclude")){
       children[i].parentNode.removeChild(children[i]);
   }
};

I would like it to loop through all children's children, etc (not just the top level). I found this line, which seems to do that:

我希望它遍历所有孩子的孩子等(不仅仅是顶级)。我找到了这条线,它似乎是这样做的:

for(var m = n.firstChild; m != null; m = m.nextSibling) {

But I'm unclear on how I refer to the current child if I make that switch? I would no longer have i to clarify the index position of the child. Any suggestions?

但是我不清楚如果我进行切换,我将如何称呼当前的孩子?我将不再需要我来澄清孩子的索引位置。有什么建议?

Thanks!

谢谢!

Update:

更新:

I'm now using the following, according to answer suggestions. Is this the correct / most efficient way of doing so?

根据回答建议,我现在正在使用以下内容。这是正确/最有效的方法吗?

function removeTest(child) {
  if (hasClass(child, "lbExclude")) {
    child.parentNode.removeChild(child);
  }
}

function allDescendants(node) {
  for (var i = 0; i < node.childNodes.length; i++) {
    var child = node.childNodes[i];
    allDescendants(child);
    removeTest(child);
  }
}

var children = temp.childNodes;
for (var i = 0; i < children.length; i++) {
  allDescendants(children[i]);
};

回答by Quentin

function allDescendants (node) {
    for (var i = 0; i < node.childNodes.length; i++) {
      var child = node.childNodes[i];
      allDescendants(child);
      doSomethingToNode(child);
    }
}

You loop over all the children, and for each element, you call the same function and have it loop over the children of that element.

您遍历所有子元素,对于每个元素,调用相同的函数并让它遍历该元素的子元素。

回答by James

Normally you'd have a function that could be called recursively on all nodes. It really depends on what you want to do to the children. If you simply want to gather all descendants, then element.getElementsByTagNamemay be a better option.

通常你会有一个可以在所有节点上递归调用的函数。这真的取决于你想对孩子做什么。如果你只是想收集所有后代,那么element.getElementsByTagName可能是一个更好的选择。

var all = node.getElementsByTagName('*');

for (var i = -1, l = all.length; ++i < l;) {
    removeTest(all[i]);
}

回答by Robbert van den Bogerd

There's no need for calling the 'allDescendants' method on all children, because the method itself already does that. So remove the last codeblock and I think that is a proper solution (á, not thé =])

不需要在所有子节点上调用 'allDescendants' 方法,因为方法本身已经这样做了。所以删除最后一个代码块,我认为这是一个正确的解决方案(á,而不是 thé =])

            function removeTest(child){     
                if(hasClass(child, "lbExclude")){
                    child.parentNode.removeChild(child);
                }
            }

            function allDescendants (node) {
                for (var i = 0; i < node.childNodes.length; i++) {
                  var child = node.childNodes[i];
                  allDescendants(child);
                  removeTest(child);
                }
            }           

            var children = allDescendants(temp);

回答by androbin

You can use BFS to find all the elements.

您可以使用 BFS 查找所有元素。

function(element) {
    // [].slice.call() - HTMLCollection to Array
    var children = [].slice.call(element.children), found = 0;
    while (children.length > found) {
        children = children.concat([].slice.call(children[found].children));
        found++;
    }
    return children;
};

This function returns all the children's children of the element.

此函数返回元素的所有子元素。

回答by kumarharsh

The most clear-cut way to do it in modern browsers or with babel is this. Say you have an HTML node $nodewhose children you want to recurse over.

在现代浏览器中或使用 babel 最明确的方法是这样。假设您有一个 HTML 节点$node,您想对其子节点进行递归。

Array.prototype.forEach.call($node.querySelectorAll("*"), function(node) {
  doSomethingWith(node);
});

The querySelectorAll('*')on any DOM node would give you allthe child nodes of the element in a NodeList. NodeListis an array-like object, so you can use the Array.prototype.forEach.callto iterate over this list, processing each child one-by-one within the callback.

querySelectorAll('*')任何DOM节点上会给你所有的元素的子节点NodeListNodeList是一个类似数组的对象,因此您可以使用Array.prototype.forEach.call来遍历此列表,在回调中逐一处理每个子项。

回答by user10794722

if items are being created in a loop you should leave a index via id="" data-name or some thing. You can then index them directly which will be faster for most functions such as (!-F). Works pretty well for 1024 bits x 100 items depending on what your doing.

如果项目是在循环中创建的,您应该通过 id="" 数据名称或其他东西留下索引。然后,您可以直接索引它们,这对于大多数函数(例如 (!-F) 而言会更快)。根据您的操作,适用于 1024 位 x 100 项。

if ( document.getElementById( cid ) ) {
 return;
} else {
  what you actually want
}

this will be faster in most cases once the items have already been loaded. only scrub the page on reload or secure domain transfers / logins / cors any else and your doing some thing twice.

在大多数情况下,一旦项目已经加载,这将更快。仅在重新加载或安全域转移/登录/ cors 时擦洗页面,并且您将某些事情做两次。

回答by Luke

If you have jquery and you want to get all descendant elements you can use:

如果您有 jquery 并且想要获取所有后代元素,则可以使用:

 var all_children= $(parent_element).find('*');

Just be aware that all_childrenis an HTML collection and not an array. They behave similarly when you're just looping, but collection doesn't have a lot of the useful Array.prototypemethods you might otherwise enjoy.

请注意,这all_children是一个 HTML 集合而不是数组。当您只是循环时,它们的行为类似,但集合没有很多Array.prototype您可能会喜欢的有用方法。

回答by Ali Chowdhury

TreeNode node = tv.SelectedNode;
while (node.Parent != null)
{
    node = node.Parent;
}                    
CallRecursive(node);


private void CallRecursive(TreeNode treeNode)`
{            
    foreach (TreeNode tn in treeNode.Nodes)
    {
        //Write whatever code here this function recursively loops through all nodes                 
        CallRecursive(tn);
    }
}

回答by wombleton

If you use a js library it's as simple as this:

如果您使用 js 库,它就像这样简单:

$('.lbExclude').remove();

Otherwise if you want to acquire all elements under a node you can collect them all natively:

否则,如果你想获取一个节点下的所有元素,你可以在本地收集它们:

var nodes = node.getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
  var n = nodes[i];
  if (hasClass(n, 'lbExclude')) {
    node.parentNode.removeChild(node);
  }
}

回答by Oded Breiner

To get alldescendants as an array, use this:

要将所有后代作为数组获取,请使用以下命令:

function getAllDescendants(node) {
    var all = [];
    getDescendants(node);

    function getDescendants(node) {
        for (var i = 0; i < node.childNodes.length; i++) {
            var child = node.childNodes[i];
            getDescendants(child);
            all.push(child);
        }
    }
    return all;
}