如果我: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 ??
如果我: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 ??
JSON(JavaScript對象 Notation)是不設計的序列化DOM節點,你需要自己拉出來你想要的東西,並將其寫入到一個對象,然後重新創建DOM節點如果你需要的話。
事實上,Chrome瀏覽器甚至不執行代碼:
TypeError: Converting circular structure to JSON
現在它返回{},而不是錯誤 – SuperUberDuper 2016-08-30 01:30:32
我做了這個樣子。我把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。
大廈阿蘭的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;
}
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已經更新了它。
查看http://stackoverflow.com/questions/2303713/how-to-serialize-dom-node-to-json – 2010-11-25 14:16:24