将树对象渲染为HTML元素

时间:2015-08-03 04:12:19

标签: javascript html

我遇到这个问题有些困难。我想在给定树结构的情况下渲染一些html元素。例如这个javascript树对象:

let htmlTree = {
    id: "a",
    children: [{
        id: "b",
        children: []
    }, {
        id: "c",
        children: [{
            id: "d",
            children: []
        }]
    }]
};

应输出如下字符串:

<a>
    <b>
    </b>
    <c>
        <d></d>
    </c>
</a>

我尝试做的是树对象的广度首次遍历(迭代),但实际上知道何时应用嵌套情况的元素的close标记。任何帮助表示赞赏,我整天都被这一切困扰:(

4 个答案:

答案 0 :(得分:2)

我知道你已经有了这方面的答案,但我认为这有助于增加讨论。 你可以让Javascript dom函数为你做繁重的工作。这在更复杂的情况下可能很有用。

function create_node(obj){
    var node = document.createElement(obj.id);
    for (var i in obj.children) {
        node.appendChild(create_node(obj.children[i]));
    }
    return node;
}
console.log(create_node({id:'root',children:[htmlTree]}).innerHTML);

JSFiddle: http://jsfiddle.net/trex005/8gxe7z3b/

注意:要获取完整的HTML,我将其包装在父节点中以使用innerHTML,因为没有跨浏览器方式获取outterHTML。

答案 1 :(得分:1)

这样就可以使字符串没有换行符......我使用var代替let以获得更多兼容性

var outputStr='';
function checkChildren(parentObj){
    outputStr+='<'+parentObj.id+'>';
    if(parentObj.children.length>0)
        parentObj.children.forEach(checkChildren);
    outputStr+='</'+parentObj.id+'>';
}
checkChildren(htmlTree);

如果你确实需要它来换行,很容易修改。 Here's a working jsfiddle

答案 2 :(得分:1)

我花了很多时间做这样的事情,在我的努力中,我构建了一个非常有效的框架,它使用了面向对象的方法,稍微复杂一点,但它允许非常快速的开发,具有类似API的界面。

  1. 使用非常简单的语法声明JSON对象,如代码所示
  2. 声明特定于对象的创建方法(Form.prototype.create)并指定如何构建对象。
  3. 然后只需调用Build() - 函数并传递JSON对象作为参数。示例---构建(登录)
  4. // CODE

        <!DOCTYPE html>
        <html>
        <head>
        <script>
        //SIMPLE JSON SYNTAX
        var signin = [
            {"container":{"element": "aside", "attributes": {"id":"overlay","class":"overlay1","onclick":"Destroy(event);"}}},
            {"form":{"element": "form", "attributes": {"id":"form"}}},
            {"msg":{"element": "mark", "attributes": {"id":"form-msg"}}},
            {"ipt1":{"element": "input", "attributes": {"type":"email","placeholder":"email","name":"email"}}},
            {"ipt2":{"element": "input", "attributes": {"type":"password","placeholder":"password","name":"password"}}},
            {"ipt3":{"element": "input", "attributes": {"type":"button","value":"Sign In","class":"form-btn btn-blue", "data-url":"/core/signin.php","onclick":"Submit(this);"}}},
            {"ipt4":{"element": "input", "attributes": {"type":"button","value":"Account Recovery","class":"form-btn btn-black","data-form":"recover","onclick":"Build(recover)"}}}
        ];
    
        //MAIN BUILD FUNCTION
        function Build(obj){
            //CREATE NEW FORM OBJECT WITH DYNAMIC PROP AND VALUES
            var form = Form.new(obj);
    
            //CREATE HTML ELEMENTS AND APPEND ITS ATTRIBUTES 
            form.assemble();
    
            //DEFINE HOW YOU WANT THE OBJECT TO BE ASSEMBLED
            form.create();
        }
    
       //DYNAMIC FORM CONSTRUCTOR
        function Form(){
            for(var i=0; i < arguments.length; i++){
                var key = Object.keys(arguments[i]);
                this[key] = arguments[i][key];
            }   
        }
       //FORM OBJECT CONSTRUCTOR METHOD (CREATE)
        Form.prototype.create = function(){
            var inpts = Object.keys(this).splice(3);
            var container = document.body.appendChild(this.container);
            var form = container.appendChild(this.form);
            container.appendChild(this.msg);
            for(i=0; i < inpts.length; i++){
                form.appendChild(this[inpts[i]]);
            }           
        }
        //GLOBAL FUNCTION METHOD (NEW)
        Function.prototype.new = function (args) {
            var Fake = Object.create(this.prototype);
            this.apply(Fake, args);
            return Fake;
        };
        //GLOBAL OBJECT METHOD (ASSEMBLE)
        Object.prototype.assemble = function(){
            for(key in this){
                if(this.hasOwnProperty(key)){
                    var element = document.createElement(this[key].element);
                    var attributes = this[key].attributes;
                    for(prop in attributes){
                        if(attributes.hasOwnProperty(prop)){
                            element.setAttribute(prop, attributes[prop]);
                            this[key] = element;
                        }
                    }   
                }
            }       
        }
        </script>
        </head>
        <body></body>
        </html>
    

答案 3 :(得分:1)

试试这个

var treeRendrer = function(treeObj,parent){
      if(treeObj && treeObj.hasOwnProperty("id")){
         parent.appendChild(document.createElement(treeObj["id"]))
      }
      if(treeObj && treeObj.hasOwnProperty("children")){
         treeObj.children.forEach(function(childObj){
            treeRendrer(childObj, parent.firstChild)
         });
      } 
    }