2012-02-28 76 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

相关问题