首先看下效果,没什么特别,呵呵!
调用的代码呢,则是相当简单,不需要创建其他的Label或者span标签,脚本将自动生成: 复制代码 代码如下: <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); } 仅供交流,欢迎大家提出指点,渴望宝贵的意见。个人觉得,即使是写简单的脚本验证程序,也应该尽量遵循面向对象的思想,并且在可扩展与效率上追寻一个协调的点,既不影响效率,同时让我们写的任何程序具有更高的可扩展性,这点思路其实不难,但是经常被很多初级程序员忽略。
推荐阅读
jQuery的.live()和.die() 使用介绍
什么是 .live() .live方法类似于.bind(),除此之外,它允许你将事件绑定到DOM元素上,可以将事件绑定到DOM中还不存在的元素上,看看下面的例子: 比方说当用户在点击链接时及想提示他们正在离开站点。 复制代码 代>>>详细阅读
本文标题:使用原生javascript创建通用表单验证——更锋利的使用dom对象
地址:http://www.17bianji.com/kaifa2/JS/24191.html
1/2 1