如何编写长可读的innerHTML

How to write long readable innerHTML?

本文关键字:innerHTML 何编写      更新时间:2023-09-26

我有一个很长的HTML块,我必须分配给innerHTML(一些服务器端ASP值添加在混合)。

在标准的"nice"布局中编写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这样的库也提供了将变量注入模板的规定。

注意,你需要加载你的模板。在开发模式下,你可以通过HTTP请求从浏览器加载这些模板,或者如果你使用Grunt、Gulp或webpack,你可以将模板构建到JavaScript应用程序文件中,这样就不需要额外的HTTP请求了。对于生产模式,你需要认真考虑将模板构建到应用负载中,以减少HTTP请求的数量。

TL;DR

尽量避免innerHTML(通过使用createElement()或createFragment()或通过切换一些可见性属性),

千万不要使用innerHTML,它会导致整个页面的布局和绘制,实际上相当于摇树