欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用原生javascript創(chuàng)建通用表單驗證——更鋒利的使用dom對象

 更新時間:2011年09月13日 21:17:10   作者:  
使用原生javascript創(chuàng)建通用表單驗證——更鋒利的使用dom對象,學(xué)習(xí)js的朋友可以參考下。

首先看下效果,沒什么特別,呵呵!


調(diào)用的代碼呢,則是相當(dāng)簡單,不需要創(chuàng)建其他的Label或者span標(biāo)簽,腳本將自動生成:

復(fù)制代碼 代碼如下:

<input type="text" id="txt1" onkeyup="checkResult(this.value == '', 'txt1', ' *這里不能為空喔!')" />

接下來我們看下這個checkResult這個函數(shù),checkCondition參數(shù)表示判斷條件,當(dāng)條件為true時顯示提示信息;showAfterId參數(shù)為創(chuàng)建的顯示提示信息的標(biāo)簽之前的元素ID,在這里我們在input后面創(chuàng)建一個span來顯示提示信息,因而 傳入的參數(shù)值為當(dāng)前input的ID“txt1”;最后一個參數(shù)為顯示的文字,這個就不用啰嗦了。
復(fù)制代碼 代碼如下:

//驗證不能為空展示提示信息
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 if (!checkCondition) {
if (document.getElementById(showLabelId))
document.getElementById(showLabelId).innerHTML = '';
}
}

好,最后我們來看這個“createShowElement(currentId, elementId, style, showMsg, tagName)”函數(shù):currentId即當(dāng)前標(biāo)簽的ID;elementId為創(chuàng)建的標(biāo)簽的ID;style為創(chuàng)建的標(biāo)簽的樣式,按照樣式的寫法即可;showMsg不講了;tagName為創(chuàng)建的標(biāo)簽名,如label或者span等。
復(fù)制代碼 代碼如下:

//創(chuàng)建展示提示信息的dom
function createShowElement(currentId, elementId, style, showMsg, tagName) {
if (!tagName) tagName = 'label';
var currentDom = document.getElementById(currentId);
var showMsgDom = document.createElement(tagName);
//showMsgDom.setAttribute("style", "color:" + textColor + ";");
if (style)
showMsgDom.setAttribute("style", style);
showMsgDom.setAttribute("id", elementId);
showMsgDom.innerHTML = showMsg;
currentDom.parentNode.insertBefore(showMsgDom, currentDom.nextSibling);
}

僅供交流,歡迎大家提出指點,渴望寶貴的意見。個人覺得,即使是寫簡單的腳本驗證程序,也應(yīng)該盡量遵循面向?qū)ο蟮乃枷?,并且在可擴展與效率上追尋一個協(xié)調(diào)的點,既不影響效率,同時讓我們寫的任何程序具有更高的可擴展性,這點思路其實不難,但是經(jīng)常被很多初級程序員忽略。

相關(guān)文章

最新評論