我已经尝试了createTextNode的每个换行符,但是我不能

时间:2019-08-02 18:21:08

标签: javascript

/n在我的代码上不起作用,因为它不会打印出换行符。请帮忙!

</br>不起作用

<script> 
        var x = document.createElement("TABLE");
        x.setAttribute("id", "myTable");
        document.body.appendChild(x);

        var y = document.createElement("TR");
        y.setAttribute("id", "myTr");
        document.getElementById("myTable").appendChild(y);

        var z = document.createElement("TD");

        var column = 1
        for(row = 1; row < 13; row++){
            var product = column*row;
            if(column != 13){
                var t = document.createTextNode(product + " ")
                if(row == 12){
                    column += 1
                    var t = document.createTextNode(product + " \u000a" + column)
                    row = 1;
                }
            }
            else if(column == 13){
                break
            }
            z.appendChild(t);
            document.getElementById("myTr").appendChild(z);
        }
    </script>

这就是我得到的:

1 2 3 4 5 6 7 8 9 10 11 12 24 6 8 10 12 14 16 18 20 22 24 36 9 12 15 18 21 24 27 30 33 36 48 12 16 20 24 28 32 36 40 44 48 510 15 20 25 30 35 40 45 50 55 60 612 18 24 30 36 42 48 54 60 66 72 714 21 28 35 42 49 56 63 70 77 84 816 24 32 40 48 56 64 72 80 88 96 918 27 36 45 54 63 72 81 90 99 108 1020 30 40 50 60 70 80 90100 110 120 1122 33 44 55 66 77 88 99 110121 132 1224 36 48 60 72 84 96 108 120 132 144 13

1 个答案:

答案 0 :(得分:1)

问题是您要制作一个带有单个表行的表。 如果您希望它位于多行中,则需要多个tr

这是您目前拥有的。

<table id="myTable">
  <tr id="myTr">1\n 2\n 3\n</tr>
</table>

这就是您想要的。

<table id="myTable">
   <tr id="myTr">1 2 3 4</tr>
   <tr>3 4 5 6</tr>
</table>

您可以尝试研究以下代码作为示例

这将创建一个数字表1-50,具有5行和10列。

我不建议使用\t来分隔或可视化内容。您应该考虑使用CSS来设置间距样式和其他样式。

var table = document.createElement("table");
table.setAttribute("id", "myTable");

const ROWS = 5;
const COLUMNS = 10;

var product = 1;

for (var i = 0; i < ROWS; i++) {
    // Create the rows element
    var row = document.createElement("tr");

    for (var j = 0; j < COLUMNS; j++) {
        // Put the "product" in the row. \t is the tab seperator, for easy view.
        row.appendChild(document.createTextNode(product+"\t"));
        product += 1;
    }

    // Append the row with the data in the table.
    table.appendChild(row);
}

// Append the table to the body element to view.
document.body.appendChild(table);