首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 動態生成 HTML:document.write 與模板字符串最佳實踐

     編輯:程式設計綜合問答

問題

嘗試在 <script> 中直接穿插 HTML 標簽控制輸出,語法無效。

錯誤示例

<script>
if (0) { </script> <p>hello1</p> <script> } else { </script> <p>hello2</p> <script> } </script>

正確方法

1. document.write (傳統、阻塞)

<script>
if (0) {
    document.write('<p>hello1</p>');
} else {
    document.write('<p>hello2</p>');
}
</script>

2. DOM 操作 (推薦、非阻塞)

<div id="container"></div>
<script>
var html = condition ? '<p>hello1</p>' : '<p>hello2</p>';
document.getElementById('container').innerHTML = html;
</script>

3. 模板字符串 + 邏輯 (ES6)

const tpl = (flag) => `<p>hello${flag ? 1 : 2}</p>`;
document.getElementById('container').innerHTML = tpl(condition);

避坑指南

  • document.write 在頁面加載後調用會**清空整個文檔**,僅限解析階段使用。
  • 優先使用 innerHTML、appendChild、現代框架 (Vue/React) 進行聲明式渲染。
  • 動態生成 HTML 時注意 **XSS 防護**,對用戶輸入進行轉義。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved