javascript 执行多行的innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30148661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
innerHTML to execute multiple lines
提问by Ravi Kishore
Iam using innerHTML in script part of my HTML file.
我在我的 HTML 文件的脚本部分使用了 innerHTML。
document.getElementById("id1").innerHTML="<font size=4 color=blue><b>Process</b></font><br>"
If it fites in single line ,it is working great, but I want to place multiple lines of HTML code in innerHTML , Is it possible ?
如果它适合单行,则效果很好,但我想在 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
";
回答by Malachi Waisman
Use ` (backtick) instead of ' or ", it will do the job.
使用 `(反引号)代替 ' 或 ",它将完成这项工作。
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
`;
回答by T.J. Crowder
The most robust way is to use string concatenation:
最健壮的方法是使用字符串连接:
document.getElementById("id1").innerHTML =
"<font size=4 color=blue>" +
"<b>Process</b>" +
"</font>" +
"<br>";
Although you cando it with line continuations:
尽管您可以使用行延续来做到这一点:
document.getElementById("id1").innerHTML =
"<font size=4 color=blue>\
<b>Process</b>\
</font>\
<br>";
Note that leading whitespace on subsequent lines ispart of the string.
请注意,后续行中的前导空格是字符串的一部分。
All that said: If you're doing this a lot, you might consider using a templating engine or similar, so you don't have your HTML intermixed with your JavaScript.
综上所述:如果您经常这样做,您可能会考虑使用模板引擎或类似引擎,这样您的 HTML 就不会与 JavaScript 混合在一起。