在javascript中递归构建HTML

时间:2016-07-11 16:34:08

标签: javascript html recursion

我有以下结构:

var struct = [{
    "name": "Name1",
    "type": "type1",
    "children": [{
        "name": "Name11",
        "type": "type1",
        "children": [{
            "name": "Name111",
            "type": "type1"
            },
            {
            "name": "Name112",
            "type": "type2"
            }
        }]
    }]
}];

我以递归方式迭代它,相应地创建HTML代码:

var build = function (data) {
        var html = '';
        for (var i in data) {
            if (data[i].type == "type1") {
                html += '<table><tr><td>' + data[i].name + '</td></tr></table>';
            } else if (data[i].type == "type2") {
                html += '<li>' + data[i].name + '</li>';
            }
            if (data[i].type == "type2") {
                html += '<tr><td colspan="4"><table class="table">';
                html += build(data[i].children);
                html += '</table></td></tr>';
            }

        }
        return html;
    };

它可以工作并提供正确的结果,但我想将这些HTML字符串重写为使用javascript函数构建HTML。但那时它不起作用。我怎么能这样做?

这就是我一直在尝试做的事情:

var build = function (data) {
        var elements = [];
        for (var i in data) {
            var element;
            if (data[i].type == "type1") {
                var table = document.createElement('table');
                var tr = document.createElement('tr');
                var td = document.createElement('td');
                td.innerHTML = data[i].name;
                tr.appendChild(td);
                table.appendChild(tr);
                element = table;
            } else if (data[i].type == "type2") {
                var li = document.createElement('li');
                li.innerHTML = data[i].name;
                element = li;
            }
            elements.push(element);
            if (data[i].type == "type2") {
                var els = document.createElement('table'); // to shorten the code
                els.innerHTML = data[i].children;
                elements.push(build(els));
            }

        }
        return elements;
    };

0 个答案:

没有答案