2012-02-28 122 views
-1

好吧,我有這個空白的對象數組。 我正在動態地查找網頁中的每個節點,並且每個節點都將擁有它自己的對象和屬性。 我需要一種方法將我需要的值放入其各自的對象屬性中將數據推送到對象數組中

因此,例如,我找到了body節點。我現在有一個特殊的小對象用於這個節點。我需要把這個小傢伙的一切都投入到他的物體的屬性中。

所以我非常需要它來呈現這樣的:

談到這一點:

<html> 
    <body style="margin:0; padding:0;" title="My Title"> 
     <p>some text</p> 
     <div class="wrapper"></div> 
     <footer></footer> 
    </body> 
</html> 

進入這個:

this.nodesInfo = [ // All nodes in the page's DOM 
    { 
     type: 'body', // ex: body, section, aside, div, etc. 
     id: 'myID', // the Id of that element 
     class: ['myClass1', 'myClass2'], // the class/class' of that element 
     depth: '2', // the level in the page's DOM in which that element sits, this will be an integer 
     parent: 'html', // that elements direct parent Node 
     children:['div.wrapper', 'p', 'footer'], // any child Nodes that, that element may be a parent to 
     text: '', // the text inside that element if any exists 
     attributes: ["style=margin:0; padding:0;", "title='My Title'"] // all attributes of this node 
    } 
]; 

它將通過每個節點當然週期才發現,和相應地爲每個節點執行此操作,直到耗盡節點。

類,兒童,和屬性性質對於任何這些倍數的簡單的可能性陣列。其他的只是一個字符串,因爲節點不能有多個ID,標題或直接父標記。

如果一個節點不包含一些屬性則該屬性將保持空白/空/未定義。


我的問題很簡單。這是否可能,如果不是,我將不得不單獨創建每個對象,並將它們推入我的nodesInfo陣列中?

我覺得去這將使得每個節點的對象,然後將它們推所有(一旦它們都創建)到一個數組的最簡單的方法。

+1

爲什麼你需要這個?有一個名爲[The DOM]的資源(https://developer.mozilla.org/en/DOM/About_the_Document_Object_Model)。 – paislee 2012-02-28 06:03:46

+0

我前幾天做了這樣的事情,查看我的答案。 – elclanrs 2012-02-28 06:23:47

+0

@paislee我正在研究一個項目,以幫助更好地可視化網站DOM地圖。我認爲在CSS和jQuery交互和操作方面,這將有助於該網站DOM的導航。但感謝無用的評論。 =) – 2012-02-28 06:33:52

回答

1

我在另一個夜晚正在建造像這樣的東西。這應該工作,你可以輕鬆地添加更多的東西。 http://jsfiddle.net/elclanrs/UHbMa/

$.fn.buildTree = function() { 
    var tree = {}; 
    this.find('*').andSelf().each(function(i, v) { 
     var parents = $(this).parents().length - 1, 
      depth = 0; 
     while (depth < parents) { 
      depth++; 
     } 
     tree[v.tagName.toLowerCase() + '(' + i + ')'] = { 
      id: (v.id) ? '#' + v.id : '', 
      className: (v.className) ? '.' + v.className.replace(' ', '.') : '', 
      depth: depth 
     }; 
    }); 
    return tree; 
}; 


// Then you can do this... 

var tree = $('#element').buildTree(); 
for (var tag in tree) { 
    // Get your variables 
    var tag.match(/\w+/), // Get rid of `(n)` 
     id = tree[tag].id, 
     className = tree[tag].className, 
     depth = tree[tag].depth; 
    html = 'something'; 

    // Bla bla 
} 
+0

我想這最終會爲每個節點創建我的對象,所以我可以將它們推入我的數組中。我想這將不得不現在工作,或者至少在我(或任何其他人)能夠想出不同的解決方案之前。謝謝! = D – 2012-02-28 06:36:33

+0

好吧,它基本上接受你想要扔進的任何對象的集合,並且你得到一個帶有與集合一樣多的標籤的大型'tree'對象,每個'tag'都是一個具有屬性本身的對象。你可以無限擴展......我在另一個晚上發佈了這個代碼。 – elclanrs 2012-02-28 06:38:46

+0

是的,那天晚上我正在尋找我正在建造的東西。我從來沒有找到它,所以我決定開始建造它。此外,我注意到一個錯誤,它似乎並沒有記錄subChild1中3個div的存在。 (另一個孩子1,2和3)。儘管如此,我還沒有弄清楚爲什麼。 – 2012-02-28 06:44:11

相關問題