2012-03-03 59 views
0

我已经得到了我该功能如何获得DOM

function traverseSVG(root){ 
    var stack = [root]; 
    var c; 
    var item = new Item("root"); 
    item.parent = item; 

    while(stack.length > 0){ 
     c = stack[ stack.length - 1 ]; 
     if(c.nodeType == 1 && c.childNodes.length > 0){ 
      stack.push(c.firstChild); 
     } else if(c.nextSibling != null){ 
      stack.pop(); 
      stack.push(c.nextSibling); 
     } else { 
      while(stack.length > 0){ 
       c = stack.pop(); 
       if(c.nextSibling != null){ 
        stack.push(c.nextSibling); 
        break; 
       } 
      } 
     } 
    } 
} 

内iterativly穿越在项目变量我喜欢来存储符合一定条件的一些元素的* .svg文件的摘录。该项目变量具有下面的构造:

function Item(e) { 
    this.e = e; 
    this.children = []; 
    this.parent = null; 
} 
Item.prototype.addChild = function(c){ 
    this.children.push(c); 
    c.setParent(this); 
    return c; 
} 
Item.prototype.setParent = function(p){ 
    this.parent = p; 
    return p; 
} 

例如,如果输入的SVG看起来是这样的:sample svg,比该项目应保存所有组和路径元素,注意等级秩序。所以在新树中,不应该包含defs元素,但defs元素中的组应该成为defs父元素的直接子元素。这就像输入DOM的提取。

请考虑,如果输入的元素应该包含在新的DOM中,那么还有一个测试函数返回true或false。我的问题是:我如何将这个包含在遍历函数中,最好?问题是跟踪正确的当前项目,当遍历在DOM中更深入时,再次出现。我尝试了很多,但没有办法解决这个问题。

感谢您的帮助!

问候菲利普

回答

0

所以,大脑扭我做了它的工作的一段时间后。只是大家谁可能来实现一些类似的任务,这里是我的解决方案:

function traverseSVG(root){ 
    var stack = [root]; 
    var c, i; 
    var item = new Item(root); 
     item.parent = item; 

    while(stack.length > 0){ 
     i = null; 
     c = stack[ stack.length - 1 ]; 

     if(Item.isItem(c) && item.canAppend){ 
      i = new Item(c); 
      item.addChild(i); 
     } 


     if(c.nodeType == 1 && c.childNodes.length > 0){ 
      stack.push(c.firstChild); 

      if(i != null){ 
       item = i; 
      } 

     } else if(c.nextSibling != null){ 
      stack.pop(); 
      stack.push(c.nextSibling); 

     } else { 
      while(stack.length > 0){ 
      c = stack.pop(); 

      if(c === item.e){ 
       item = item.parent; 
      } 

       if(c.nextSibling != null){ 
       stack.push(c.nextSibling); 
       break; 
      } 
     } 
    } 
} 

}

使用变量i的新项目并获得成功。问候...