我有一个很长的 HTML block ,我必须分配给 innerHTML(在混合中添加了一些服务器端 ASP 值)。
在标准的“漂亮”布局中编写 HTML 是否有任何好的做法 - 例如,使用适当的缩进 - 以便可以将其分配给 innerHTML?
(我们不能假设将始终使用特定的 IDE 或代码编辑器。)
举个例子:这是我在重构代码时经常遇到的一种模式:
<SCRIPT LANGUAGE="JavaScript">
<!--
window.opener.document.getElementById("overlay").style.position = "fixed";
window.opener.document.getElementById("overlay").style.width = "700px";
window.opener.document.getElementById("overlay").style.top = "100px";
window.opener.document.getElementById("overlay").innerHTML = "<DIV STYLE=\"margin:25px 0px -10px 0px\"><DIV CLASS=\"error\" STYLE=\"height:auto; background:#ffe5e5; background-image:url(/images/icon_alert.png); background-position:5px 5px; background-repeat:no-repeat; border:1px solid #c00; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; margin:10px 0px; padding:10px 10px 10px 35px; color:#c00\">There was a problem ... ;
最佳答案
一种解决方案是使用客户端模板,例如 Handlebars与 jQuery 一起。然后,您可以在单独的 .html 文件中保持 HTML 的良好格式,并与其余代码完全分开。 Handlebars 等库还提供了将变量注入(inject)模板的规定。
请注意,您需要加载模板。在开发模式下,您可以通过来自浏览器的 HTTP 请求加载它们,或者如果您使用的是 Grunt、Gulp 或 webpack,则可以将模板构建到 JavaScript 应用程序文件中,这样就不需要额外的 HTTP 请求。对于生产模式,您需要认真考虑将模板构建到您的应用负载中,以尽量减少 HTTP 请求的数量。
关于javascript - 如何写长可读的innerHTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39155089/