把頁面的某些區塊抽成獨立 HTML 檔再動態載入,能讓結構更清楚、維護更方便。本文示範如何用 jQuery 的 load 方法,把外部 HTML 內容載入到指定的 DIV 中。
<script src="js/jquery.js"></script>
<script>
$(function(){
$("div#top_sidebar").load("top_sidebar.html");
})
</script>
其中 #top_sidebar 是目標 DIV 的 ID,load 方法會把 top_sidebar.html 的內容抓取回來並插入這個容器。當頁面 DOM 就緒後便自動執行,非常適合用在側邊欄、頁首等固定區塊的組裝。