嘗試在 <script> 中用條件語句直接包裹 HTML 標籤,語法錯誤:
<script> if (0) { </script>
<p>hello1</p>
<script> } else { </script>
<p>hello2</p>
<script> } </script> // ❌ HTML 不能斷開在 script 標籤間
<script>
if (0) {
document.write('<p>hello1</p>');
} else {
document.write('<p>hello2</p>');
}
</script>
<div id="container"></div>
<script>
const html = condition ? '<p>hello1</p>' : '<p>hello2</p>';
document.getElementById('container').innerHTML = html;
</script>
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)更易維護。