首頁
編程語言
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> // ❌ HTML 不能斷開在 script 標籤間

方案一:document.write(簡單、阻塞)

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

方案二:模板字符串 + innerHTML(推薦)

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

方案三:DOM API 創建元素(最規範)

const container = document.getElementById('container');
const p = document.createElement('p');
p.textContent = condition ? 'hello1' : 'hello2';
container.appendChild(p);

注意

  • document.write 頁面加載後調用會覆蓋整個文檔,**僅適用於加載階段**;
  • 動態內容優先用 innerHTML 或 DOM API,配合模板引擎(如 Handlebars、Vue/React JSX)更易維護。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved