本系列前面談過 Prototype 的基礎類別、列舉物件與 AJAX 請求。這一篇回頭看一個很實用的主題:怎麼把 HTML 片段精準插入到頁面的指定位置。Prototype 用四個 Insertion 類別把這件事包得很乾淨。
建立 Insertion.Before 的實例,會把指定的 HTML 加到目標元素之前,並與之相鄰(是兄弟關係,不是子元素)。
<div id="div1">original text</div>
<script>
// 執行後頁面變成:new text<div id="div1">original text</div>
new Insertion.Before("div1", "new text");
</script>
指定 HTML 會被加到目標元素內部,位置在開始標籤之後。
<div id="div1">original text</div>
<script>
// 執行後 div1 的 innerHTML 是:new text original text
new Insertion.Top("div1", "new text");
</script>
指定 HTML 會被加到目標元素內部,位置在結束標籤之前。
<div id="div1">original text</div>
<script>
// 執行後 div1 的 innerHTML 是:original text new text
new Insertion.Bottom("div1", "new text");
</script>
指定 HTML 會被加到目標元素之後,同樣是兄弟關係。
<div id="div1">original text</div>
<script>
// 執行後頁面變成:<div id="div1">original text</div>new text
new Insertion.After("div1", "new text");
</script>
把 Before / After 想成「元素的左右鄰居」,Top / Bottom 想成「元素內部的最前與最後」,就不會搞混:
Before
┌──── <div> ────┐
│ Top │
│ 內容 │
│ Bottom │
└────────────────┘
After
Prototype 也對表單做了擴充,例如 Field.clear() 用來清空指定欄位的值:
Field.clear('username'); // 把 id 為 username 的欄位清空
這類表單輔助方法在 Prototype 裡還有不少(如 Field.focus()、Form.serialize()),後續篇章會再談。
補充一個現實面的提醒:Insertion 系列在 Prototype 1.6 之後已被 Element.insert() 取代,寫法更直覺:
$('div1').insert({ before: 'new text' });
$('div1').insert({ after: 'new text' });
$('div1').insert({ top: 'new text' });
$('div1').insert({ bottom: 'new text' });
如果你是在讀舊專案,認得 Insertion 這四兄弟就夠了;如果是新專案,直接用 insert()。而如果今天你手上是 jQuery,對應的方法分別是 .before()、.after()、.prepend() 與 .append()——觀念完全相通。