Html javascript 中的代码无法使用 document.write

Html code in javascript not working using document.write

我只在 html 中尝试过此代码,它可以正常工作,但在使用 document.write 时它根本不执行。 notepad++ 将该代码着色为黑色直到 img 标签(包括 img)。 我是新手,我无法识别其中的错误。

代码:

<script type="text/javascript" language="javascript">
document.write("
<table valign="middle" width="100%" height="100%" border="0" cellpadding="15%" >
    <tr align="center" valign="middle" height="50%" >
        <td><img src="images/logo.png" ></td>
    </tr>
    <tr height="10%">
        <td colspan=2>
            <input type="text" id="eno" maxlength="9" size="9" placeholder="Enrollment No." style="border:0;font-size:72;width:100%;height:100%;">
        </td>
    </tr>
    <tr height="10%">
        <td colspan=2>
            <input type="button" value="Enter" onclick="SaveEno()" style="font-size:72;color:white;background-color:black;width:100%;height:100%;border:0;">
        </td>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>
");
</script>

在这种情况下,document.write("") 会考虑换行符、双引号等标签的格式。因为它不是 javascript 字符串,所以不要使用双引号。为此,请在 document.write(``) 函数中添加所有标签。更多https://www.w3schools.com/jsref/met_doc_write.asp

HTML 片段中的双引号干扰了 JavaScript。除非您需要支持 Internet Explorer,否则您真的应该使用 template literal。如果是这样,您要么必须在 HTML 片段周围使用单引号,要么转义其中的所有双引号 \".

document.write(`
    <table valign="middle" width="100%" height="100%" border="0" cellpadding="15%" >
        <tr align="center" valign="middle" height="50%" >
            <td><img src="images/logo.png" ></td>
        </tr>
        <tr height="10%">
            <td colspan=2>
                <input type="text" id="eno" maxlength="9" size="9" placeholder="Enrollment No." style="border:0;font-size:72;width:100%;height:100%;">
            </td>
        </tr>
        <tr height="10%">
            <td colspan=2>
                <input type="button" value="Enter" onclick="SaveEno()" style="font-size:72;color:white;background-color:black;width:100%;height:100%;border:0;">
            </td>
        </tr>
        <tr>
            <td></td>
        </tr>
    </table>
    `);