2011-05-21 118 views
2

我使用的是火狐4 JS并获得“太多的递归错误”,为下面的代码:太多的递归调用

extractText: function(domObj) { 
    if (domObj == null) { 
     return ""; 
    } else { 
     var acc = ""; 
     if (domObj.nodeType == Node.TEXT_NODE) { 
      acc += domObj.nodeValue; 
     } 
     if (domObj.hasChildNodes()) { 
      var children = currentObj.childNodes; 
      for (var i = 0; i < children.length; i++) { 
       acc += sui.extractText(children[i]); 
      } 
     } 
     return acc; 
    } 
    } 
}; 

有人吗?

+2

“currentObj”和“sui”在哪里定义? – Blender 2011-05-21 15:43:01

+0

这不是有效的Javascript。请张贴实际的测试用例。 – 2011-05-21 15:54:23

+0

currentObj是我的问题,错误的变量 - 愚蠢的我:-) – eve 2011-05-21 16:11:34

回答

3

我觉得这条线:

 var children = currentObj.childNodes; 

应该是:

 var children = domObj.childNodes; 

在我看来,就好像你提到“currentObj”在顶部重新开始,而不是从降元素正在检查中。当然很难说,因为你没有包含“currentObj”的相关定义或初始化。

+0

我认为你是对的。 – 2011-05-21 15:53:55

+0

嘿,那是对的!谢谢。然而,没有我有一个不同的问题,并获得不是文本的东西,如:#hdr-editions a {text-decoration:none; } #cnn_hdr-editionS {text-align:left; clear:both; } 任何人? #cnn_hdr-editionS {text-decoration:none; font-size:10px; top:7px; line-height:12px; font-weight:bold; } #hdr-prompt-text b {display:inline-block; margin:0 0 0 20px; } #hdr-editions li {padding:0 10px; } #hdr-editions ul li.no-pad-left span {font-size:12px; } .hdr-arrow-intl,.hdr-arrow-us,.hdr-arrow-us2 {left:148px; } .hdr-arrow-us2 {left:180px; } – eve 2011-05-21 22:00:10

+0

@eve这是另一个问题了...不要在评论中提问。但我确定这是因为文档中有嵌入式样式......很难说,因为您没有在您的问题中提供相关代码。 – Salketer 2015-10-06 12:43:32

0

您也可以尝试一种迭代的方法,而不是递归的:

extractText: function(domObj) { 
    if (!(domObj instanceof Node)) return null; 
    var stack = [domObj], node, tf = []; 
    while (stack.length > 0) { 
     node = stack.pop(); 
     switch (node.nodeType) { 
     case Node.TEXT_NODE: 
      tf.push(node.nodeValue); 
      break; 
     case Node.ELEMENT_NODE: 
      for (var i=node.childNodes.length-1; i>=0; i--) 
       stack.push(node.childNodes[i]); 
      break; 
     } 
    } 
    return tf.join(""); 
} 

该算法使用堆栈仍然必须要访问的节点实现depth first search。如果是Node instance,堆栈中的第一项是domObj。然后,对于堆栈中的每个节点:如果它是一个Text node,则将其值添加到文本片段数组tf;如果是Element node,则其子节点以相反的顺序放置在堆栈上,以便第一个子节点位于堆栈顶部。重复这些步骤直到堆栈为空。最后,使用数组的join方法将tf中的文本片段放在一起。