簡體   English   中英

使用縮進序列化動態創建的html

[英]serializing dynamically created html with indentation

在使用appendChild()在html文檔中創建了一堆元素之后,我試圖將修改后的頁面保存在客戶端上。 將其發送到服務器似乎沒有必要,所以我選擇了:

var save = document.createElement("a");

save.classList.add("button");
save.textContent = "save";
save.download = "layout-save.html"
save.onclick = function(event) {
    var output = [];

    // serialize document to output

    var file = new window.Blob(output,{type:"text/html"});
    save.href = window.URL.createObjectURL(file);
}

document.body.appendChild(save);

但是,新創建的元素當然不會縮進。 我一直在看js-beautify,但我也注意到有關解析和序列化mozilla頁面聲稱可以使用treewalker。

有人知道我會怎么做嗎? 否則,將有一種方法可以在沒有子節點的情況下序列化節點,以運行如下所示的遞歸循環:

var output = [];
var serializer = new XMLSerializer();

function indent(node) {
    var ancestor = node;

    while (ancestor != document.documentElement) {
        output.push("   ");
        ancestor = ancestor.parentNode;
    }

    output.push(/* serialize node tagname + attributes */);
    output.push("\n");

    for (let child of node.children) {
        indent(child);
    }

    output.push(/* node closing tag*/);
}

indent(document.documentElement);

不要猶豫告訴我,如果我在錯誤的樹上吠叫,並感謝您的寶貴時間。

通過回答我自己的問題,您可以序列化淺表克隆以獲取節點的開始和結束標簽:

var save = document.createElement("a");

save.classList.add("button");
save.textContent = "save";
save.download = "layout.html"
save.onclick = function(event) {
    document.body.removeChild(save);

    var output = [];
    var serializer = new XMLSerializer();

    function indent(node) {
        function offset(node) {
            var count = 0;
            var ancestor = node;

            while (ancestor != document.documentElement) {
                count++;
                ancestor = ancestor.parentNode;
            }
            return "\t".repeat(count);
        }

        var buffer = offset(node);
        var nodeClone = serializer.serializeToString(node.cloneNode(false)).replace(' xmlns="http://www.w3.org/1999/xhtml"',"");

        if (node.children.length) {
            let tagSplit = nodeClone.replace(/(<.+>)(<\/.+>)/,"$1<!--children-->$2").split("<!--children-->");

            output.push(buffer + tagSplit[0] + "\n");

            for (let child of node.children) {
                indent(child);
            }

            output.push(buffer + tagSplit[1] + "\n");
        } else {
            output.push(buffer + nodeClone + "\n");
        }
    }

    indent(document.documentElement);

    var file = new window.Blob(output,{type:"text/html"});
    save.href = window.URL.createObjectURL(file);
}

document.body.appendChild(save);

手動刪除xhtml命名空間有點可惜,但是由於它是XMLSerializer,所以我看不到任何解決方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM