0

基本上,我希望用户只需将“高度”变量更改为他想要的行数,然后存储行中每个 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>

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

4

2 回答 2

2

你应该换行

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

进入

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

您正在内部循环中再次添加 Tr 代码,但您实际上想要添加 Td 代码。

于 2013-10-28T15:16:51.630 回答
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

于 2013-10-28T15:24:49.533 回答