我在HTML文件的脚本部分使用innerHTML。
document.getElementById("id1").innerHTML="<font size=4 color=blue><b>Process</b></font><br>"
如果它单行,它工作得很好, 但我想在innerHTML中放置多行HTML代码,是否可能?
document.getElementById("demo").innerHTML = "
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CPU Information
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
No of Cores:
1
Speed of each core in Mhz:
cpu MHz : 2399.318
model name : Intel(R) Xeon(R) CPU E5645 @ 2.40GHz
CPU Load:
0.1
Top CPU using process/application
-------------------------------------
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 15 0 10364 680 576 S 0.0 0.0 0:05.46 init
";
答案 0 :(得分:4)
最强大的方法是使用字符串连接:
document.getElementById("id1").innerHTML =
"<font size=4 color=blue>" +
"<b>Process</b>" +
"</font>" +
"<br>";
虽然可以使用续行符号
document.getElementById("id1").innerHTML =
"<font size=4 color=blue>\
<b>Process</b>\
</font>\
<br>";
请注意,后续行上的前导空格是字符串的一部分。
所有这一切:如果您经常这样做,可以考虑使用模板引擎或类似功能,这样您就不会将HTML与JavaScript混合在一起。
答案 1 :(得分:2)
使用`(反引号)代替&#39;或&#34;,它将完成这项工作。
document.getElementById("demo").innerHTML = `
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CPU Information
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
No of Cores:
1
Speed of each core in Mhz:
cpu MHz : 2399.318
model name : Intel(R) Xeon(R) CPU E5645 @ 2.40GHz
CPU Load:
0.1
Top CPU using process/application
-------------------------------------
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 15 0 10364 680 576 S 0.0 0.0 0:05.46 init
`;