无法以 HTML 格式打印表格

我正在尝试使用 JavaScript 在 HTML 中打印表格。当我尝试打印表格时,它只是给我一个空白页。这是我的 HTML 代码:


<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <script type="text/javascript" src="gen.js"></script>

    <link rel="stylesheet" href = "index.css">

</head>

<body onload="print()">

    <div id="tt"></div>

</body>

</html>

这是我的 JavaScript 文件:


function print(){

    // console.log("?")

    var time = Number(localStorage.getItem("time"))

    // console.log(typeof time)

    var nClass = Number(localStorage.getItem("nClass"))

    var duration = localStorage.getItem("duration")

    var subjectsRaw = localStorage.getItem("arr")

    var subjects = JSON.parse(subjectsRaw)

     document.getElementById('tt').innerHTML = "<table border = 1>"

for(var i = 0; i < 5; i++){

    console.log('test')

    document.getElementById('tt').innerHTML = "<tr>"

    for (let j = 0; j < nClass; j++) {

        console.log('test2')

        document.getElementById('tt').innerHTML = '<td>' + subjects[Math.floor(Math.random() * subjects.length + 0)] + '</td>'

        

    }

    document.getElementById('tt').innerHTML = "</tr>"

    document.getElementById('tt').innerHTML = "<br>"

}

document.getElementById('tt').innerHTML = "</table>"

编辑:现在使用 DOM 打印。


子衿沉夜
浏览 126回答 1
1回答

缥缈止盈

每次分配给时都会覆盖该元素innerHTML,而不是附加到它。您不能像使用 DOM 方法那样逐步构建 HTML,因为每次分配给innerHTML它时都会将其解析为完整的 HTML 片段。innerHTML您应该改为附加到一个字符串,并在末尾分配给。function print() {&nbsp; // console.log("?")&nbsp; var time = Number(localStorage.getItem("time"))&nbsp; // console.log(typeof time)&nbsp; var nClass = Number(localStorage.getItem("nClass"))&nbsp; var duration = localStorage.getItem("duration")&nbsp; var subjectsRaw = localStorage.getItem("arr")&nbsp; var subjects = JSON.parse(subjectsRaw)&nbsp; var html = "<table border = 1>"&nbsp; for (var i = 0; i < 5; i++) {&nbsp; &nbsp; console.log('test')&nbsp; &nbsp; html += "<tr>"&nbsp; &nbsp; for (let j = 0; j < nClass; j++) {&nbsp; &nbsp; &nbsp; console.log('test2')&nbsp; &nbsp; &nbsp; html += '<td>' + subjects[Math.floor(Math.random() * subjects.length + 0)] + '</td>'&nbsp; &nbsp; }&nbsp; &nbsp; html += "</tr>"&nbsp; }&nbsp; html += "</table>"&nbsp; document.getElementById("tt").innerHTML = html;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript