嘗試在 <script> 中直接穿插 HTML 標簽控制輸出,語法無效。
<script>
if (0) { </script> <p>hello1</p> <script> } else { </script> <p>hello2</p> <script> } </script>
<script>
if (0) {
document.write('<p>hello1</p>');
} else {
document.write('<p>hello2</p>');
}
</script>
<div id="container"></div>
<script>
var html = condition ? '<p>hello1</p>' : '<p>hello2</p>';
document.getElementById('container').innerHTML = html;
</script>
const tpl = (flag) => `<p>hello${flag ? 1 : 2}</p>`;
document.getElementById('container').innerHTML = tpl(condition);
document.write 在頁面加載後調用會**清空整個文檔**,僅限解析階段使用。innerHTML、appendChild、現代框架 (Vue/React) 進行聲明式渲染。