创建嵌套表

时间:2013-03-01 16:23:02

标签: javascript html dom html-table

美好的一天。我正在尝试创建嵌套表一百次。但是,我的代码创建了一个主表,然后在其中,有100个单独的表。 (感谢萨钦爵士的帮助)我需要的是桌子内的桌子。请帮我修复代码。

<html>
<head> <title> Hello! </title> 

<script type="text/javascript">
function add() { 
    var ni = document.getElementById('myDiv');
    var numi = document.getElementById('theValue');
    var num = (document.getElementById('theValue').value -1)+ 2;
    numi.value = num;
    var newdiv = document.createElement('div');
    var divIdName = 'my'+num+'Div';
    newdiv.setAttribute('id',divIdName);
    newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value=1 id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
    ni.appendChild(newdiv);
    for(var i=1;i<100;i++) {
        var ni = document.getElementById(divIdName);
        var numi = document.getElementById('theValue');
        var num = (document.getElementById('theValue').value -1)+ 2;
        numi.value = num;
        var newdiv = document.createElement('div');
        var divIdName = 'my'+num+'Div';
        newdiv.setAttribute('id',divIdName);
        var j=i++;
        newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='" + j + "' id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
        ni.appendChild(newdiv);
    }
}
</script>

</head>
<body onload="add()">
<table border="1">
    <tr>
        <td> Hello! <input type='hidden' value='0' id='theValue' />

        <div id='myDiv'> </div> </td>
    </tr>
</table>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这应该这样做(我已经删除了隐藏的输入,因为它不需要):http://jsfiddle.net/rPR9w/1/

function add() {
    for (i=1; i<=100; i++) {
        addAnother(i);
    }
}


function addAnother(counter) { 
    var container = document.getElementById('myDiv' + counter);
    container.innerHTML = makeTable(counter + 1);
}

function makeTable(counter) {

    return "<table border=1><tr><td> Hello! <div id='myDiv" + counter + "'></td></tr></table>";

}