使用Javascript创建html表不起作用

时间:2013-10-28 15:07:21

标签: javascript html-table dynamically-generated

基本上,我希望用户只需将'height'变量更改为他想要的行数,然后存储行中每个td应包含的单词,然后代码应该生成表。

我的HTML就是这样:

    <table id="newTable">
    </table>

这是我的Javascript:

<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;

var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row

$(document).ready( function() {
    createTr();
});

function createTr () {
    for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
        var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
        $('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
        for (var i=0; i<window['height' + rowNumber].length; i++) {
            if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
                var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
                $('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr

            } else {
                var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
                $('#rowNumber' + rowNumber).append(theTr);
            }
        }
        rowNumber += 1;
    }
}
</script>

我做了'警报(theTr);'和'警告(theTd);'他们看起来很正确。为什么这段代码不生成任何表?

2 个答案:

答案 0 :(得分:2)

您应该更改

$('#rowNumber' + rowNumber).append(theTr);

进入

$('#rowNumber' + rowNumber).append(theTd);

您在内循环中再次添加Tr-Code,但实际上您想要添加Td-Code。

答案 1 :(得分:1)

所有window["height"+rowNumber]内容都是一种糟糕的方式。使用数组,并将其作为参数传递给函数,这样就不会使用全局变量。并使用jQuery DOM创建函数而不是附加字符串。

<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
               ['firstTd of row', 'secondTd of row'], // the words in each td in the second row
               ['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
              ];

$(document).ready( function() {
    createTr(heights);
});

function createTr (heights) {
    for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
        var theTr = $("<tr>", { id: "rowNumber" + h});
        for (var i=0; i<heights[h].length; i++) {
            theTr.append($("<td>", { "class": "row"+h + " column"+i,
                                     text: heights[h][i]
                                   }));
        }
        $('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
    }
}
</script>

JSFIDDLE