我试图将我的DOM保存为某种JSON格式,树中的一个键是content。这段代码运行得“很好”,但只适用于简单的情况。我使用now nodeValue只从第一个子元素中获取文本,它给了我很好的结果,但是当结构包含像br这样的元素时,它就崩溃了。
const uploadDom = (node, path, siblingsLeft, order) => {
for (let item of node) {
order = order + 1;
database.ref("dom/" + path + "/" + order).update({
id: item.id,
type: item.tagName,
class: item.className,
content: item.childNodes[0].nodeValue
});
if (item.children.length) {
siblingsLeft = item.children.length - 1;
path = path + order + `/`;
uploadDom(item.children, path, siblingsLeft, order);
}
if (siblingsLeft > 1) {
a = order + "/";
path = path.replace(a, "");
siblingsLeft = 1;
}
}
};以下是HTML结构示例:(请注意,此结构始终是动态的)
<div id="wrapper">
<!-- wrapper has no text content so I want content value of null -->
<p>I want to save this text as content value of P tag</p>
<div class="wrapper-2">
<!-- wrapper has no text content so I want content value of null -->
<p>This P contains <br> new line element</p>
<!-- I'm using nodeValue of first child so content will be = 'This P contains' -->
<!-- content should be = 'This P contains <br> new line element' -->
<p>I want to save this text as content value of P tag</p>
</div>
</div>我正在努力找出更聪明的方法来保存我的DOM树,尽管我正在为上面的例子中保存文本内容的方法而苦苦挣扎。
发布于 2019-05-08 14:26:16
您可以将DOM树保存到有效的json中,如下所示
let json = JSON.stringify(wrapper.innerHTML)
console.log(JSON.parse(json));<div id="wrapper">
<!-- wrapper has no text content so I want content value of null -->
<p>I want to save this text as content value of P tag</p>
<div class="wrapper-2">
<!-- wrapper has no text content so I want content value of null -->
<p>This P contains <br> new line element</p>
<!-- I'm using nodeValue of first child so content will be = 'This P contains' -->
<!-- content should be = 'This P contains <br> new line element' -->
<p>I want to save this text as content value of P tag</p>
</div>
</div>
https://stackoverflow.com/questions/56034613
复制相似问题