使用原生javascript创建通用表单验证——更锋利的使用dom对象 |
本文标签:表单验证 首先看下效果,没什么特别,呵呵!
复制代码 代码如下: <input type="text" id="txt1" onkeyup="checkResult(this.value == , txt1, *这里不能为空喔!)" /> 接下来我们看下这个checkResult这个函数,checkCondition参数表示判断条件,当条件为true时显示提示信息;showAfterId参数为创建的显示提示信息的标签之前的元素ID,在这里我们在input后面创建一个span来显示提示信息,因而 传入的参数值为当前input的ID“txt1”;最后一个参数为显示的文字,这个就不用啰嗦了 。 复制代码 代码如下: //验证不能为空展示提示信息 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)”函数:currentId即当前标签的ID;elementId为创建的标签的ID;style为创建的标签的样式,按照样式的写法即可;showMsg不讲了;tagName为创建的标签名,如label或者span等 。 复制代码 代码如下: //创建展示提示信息的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); } 仅供交流,欢迎大家提出指点,渴望宝贵的意见 。个人觉得,即使是写简单的脚本验证程序,也应该尽量遵循面向对象的思想,并且在可扩展与效率上追寻一个协调的点,既不影响效率,同时让我们写的任何程序具有更高的可扩展性,这点思路其实不难,但是经常被很多初级程序员忽略 。 |