2010-11-25 57 views
1

如果我:JSON序列DOM元素

var el = 
{ 
    o : document.createElement("iframe") 
} 

var fs = JSON.stringify(el); 

and then I try to access with 

var ofs = JSON.parse(fs); 

ofs.o包含一个空的对象不是iframe元素WHY ??

+0

查看http://stackoverflow.com/questions/2303713/how-to-serialize-dom-node-to-json – 2010-11-25 14:16:24

回答

6

JSON(JavaScript对象 Notation)是设计的序列化DOM节点,你需要自己拉出来你想要的东西,并将其写入到一个对象,然后重新创建DOM节点如果你需要的话。

事实上,Chrome浏览器甚至不执行代码:

TypeError: Converting circular structure to JSON 
+0

现在它返回{},而不是错误 – SuperUberDuper 2016-08-30 01:30:32

2

我做了这个样子。我把github

function elementToObject(element, o) { 
    var el = $(element); 
    var o = { 
     tagName: el.tagName 
    }; 
    var i = 0; 
    for (i ; i < el.attributes.length; i++) { 
     o[el.attributes[i].name] = el.attributes[i].value; 
    } 

    var children = el.childElements(); 
    if (children.length) { 
     o.children = []; 
     i = 0; 
     for (i ; i < children.length; i++) { 
     child = $(children[i]); 
     o.children[i] = elementToObject(child, o.children) ; 
     } 
    } 
    return o; 
    } 
/* 
    exemple: 
    a = elementToObject(document.body); 
    Object.toJSON(a); 
*/ 

该JavaScript函数的代码的任何元素转换为对象,那么你可以将其转换为JSON。

1

大厦阿兰的prototypejs码,我用下划线和jQuery,也投入要旨here

function elementToObject(element, recurse) { 
    var el = $(element), 
     o = { 
      tagName: el[0].tagName 
     }; 

    _.each(el[0].attributes, function(attribute){ 
     o[attribute.name] = attribute.value; 
    }); 

    if (recurse) { 
     o.children = _.map(el.children(), function(child){ 
      return this.elementToObject(child, true); 
     }, this); 
    } 
    return o; 
} 
1
function elementToObject(element) { 
    var el = $(element)[0]; 
    var o = {tagName: el.tagName}; 
    _.each(el.attributes, function(attribute){o[attribute.name] = attribute.value;}); 
    o["children"]=_.map($(el).children(), function(child){return elementToObject(child)}); 
    return o; 
} 

这是工作与jQuery 3.1.0和underscore.js已经更新了它。