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

问题描述 投票:-2回答:2

我只在html中尝试过此代码并且它正在工作但是在使用document.write时它根本不执行。 notepad ++将该代码着色为img tag(包括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>
javascript html document.write
2个回答
0
投票

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>
    `);

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.