有些表單需要讓使用者動態增加多個檔案上傳欄位,也能隨時移除。本文分別用原生 JavaScript 與 jQuery 實作「一鍵新增、一鍵刪除」的上傳欄位,讓你比較兩種風格。
用 document.createElement 建立節點,再 appendChild 加入容器,每個新欄位配一個移除鈕:
var addMore = function() {
var div = document.getElementById("div2");
var br = document.createElement("br");
var input = document.createElement("input");
var button = document.createElement("input");
input.setAttribute("type", "file");
button.setAttribute("type", "button");
button.setAttribute("value", "Remove");
button.onclick = function() {
div.removeChild(br);
div.removeChild(input);
div.removeChild(button);
}
div.appendChild(br);
div.appendChild(input);
div.appendChild(button);
}
用 jQuery 的語法更精簡,建立元素與移除都只要一行:
$(function(){
$("input[type=button]").click(function(){
var br = $("<br>");
var input = $("<input type='file'/>");
var button = $("<input type='button' value='Remove'/>");
$("#div1").append(br).append(input).append(button);
button.click(function() {
br.remove();
input.remove();
button.remove();
});
});
});
兩種寫法效果相同,但 jQuery 的鏈式操作讓程式碼更短、可讀性更高。實務上要留意:動態產生的元素若要綁定事件,記得在建立當下就掛上,或改用事件委派(如 on)處理。