表單驗證常需要在輸入框旁即時顯示錯誤訊息。利用原生 DOM,可以動態建立提示元素,不必在 HTML 中預先放置大量 span 或 label。

checkResult 接收條件、參考元素 id 與提示文字。當條件成立時顯示訊息,不成立時清空訊息。
function checkResult(checkCondition, showAfterId, showMsg) {
var showLabelId = showAfterId + 'showMsg';
if (checkCondition) {
if (document.getElementById(showLabelId)) {
document.getElementById(showLabelId).innerHTML = showMsg;
} else {
createShowElement(showAfterId, showLabelId, 'color:red', showMsg, 'span');
}
} else {
var el = document.getElementById(showLabelId);
if (el) el.innerHTML = '';
}
}function createShowElement(currentId, elementId, style, showMsg, tagName) {
if (!tagName) tagName = 'label';
var currentDom = document.getElementById(currentId);
var showMsgDom = document.createElement(tagName);
if (style) showMsgDom.setAttribute('style', style);
showMsgDom.setAttribute('id', elementId);
showMsgDom.innerHTML = showMsg;
currentDom.parentNode.insertBefore(showMsgDom, currentDom.nextSibling);
}這種做法讓驗證邏輯集中,易於擴充。實務上也可進一步封裝為物件,統一管理規則、訊息與顯示位置。