2012-03-03 52 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的新項目並獲得成功。問候...