如何以递归方式循环所有子项? [英] How do I make this loop all children recursively?

查看:120
本文介绍了如何以递归方式循环所有子项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

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

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

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

但我不清楚如果我指的是当前的孩子做那个开关?我不再需要澄清孩子的指数位置。有什么建议吗?



谢谢!



更新:



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

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

函数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]);
};


解决方案

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

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

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


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

解决方案

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.getElementsByTagName may be a better option.

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

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

这篇关于如何以递归方式循环所有子项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆