微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在js中写html

如何解决如何在js中写html

我想写

<body>
  <html>
    <div id="myfilter" style="position:absolute;background-color:#000000;opacity:0.3;width:100%;height:100%;display:none">
    </div>
    <div id="myrestartbutton" style="display:none;position:absolute;color:white;padding:20px;padding-top:0;border-radius:10px; top: 50%;left: 50%;transform: translate(-50%,-50%);background:Black;">
      <h1>score: 
        <span id="score">
        </span>
      </h1>
      <center>
        <button id="btn" onclick="restartGame()">Restart
        </button>
      </center>
    </div>
    <div id="canvascontainer">
    </div>
  </html>
</body>

在仅使用 JS 文件的 html 中,我希望我的 html 文件如下所示:

<script src="index.js"></script>

我想要一种纯粹的 JS 方式。

解决方法

您可以使用 document.write

document.write('<body><html><div id="myfilter" style="position:absolute;background-color:#000000;opacity:0.3;width:100%;height:100%;display:none"></div><div id="myrestartbutton" style="display:none;position:absolute;color:white;padding:20px;padding-top:0;border-radius:10px; top: 50%;left: 50%;transform: translate(-50%,-50%);background:Black;"><h1>Score: <span id="score"></span></h1> <center><button id="btn" onclick="restartGame()">Restart</button></center></div><div id="canvascontainer"></div></html></body>')
,

这样做的正确方法不是上面建议的方法。虽然它确实有效,但从技术上讲,有完整的框架可以帮助构建 HTML,客户端 Javascript 执行所有 DOM 操作。 因此,您可以以全新的方式将 JS 代码与 HTML 混合。

看看这个: https://www.w3schools.com/react/react_jsx.asp

它具有 HTML 的所有感觉,但通过 JavaScript 运行时呈现。关键是,您不必编写低级 JS 代码,而是将其外包给框架,将时间花在更高级的问题上。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。