使用原生javascript创建通用表单验证——更敏锐地使用dom对象
先看看效果,没什么特别的,呵呵!
调用代码相当简单,不创建其他Label或span标签,脚本会自动生成:复制的代码如下: inputtype=' Text ' ID=' TXT1OnKeyup=' check result(this。值==' ',' TXT11 ',' *不能为空!)'/接下来,让我们看看函数checkResult。checkCondition参数表示判断条件,当条件为真时,显示提示信息。ShowAfterId参数是为显示提示信息而创建的标签之前的元素Id。这里我们在输入后面创建一个span来显示提示信息,所以传入的参数值就是当前输入的ID“txt 11”;最后一个参数是显示的文本,所以这不需要措辞。复制代码如下: //验证不能为空。显示提示消息函数检查结果(检查条件,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(!check condition){ if(document . getelementbyid(showLabelId))document . getelementbyid(showLabelId)。innerHTML=}}好了,最后我们来看看这个“createshowelement(current tid,elementid,style,showmsg,tagname)”函数:current tid是当前标签的ID;ElementId是创建的标签的id;Style是创建的标签的样式,可以根据样式编写;ShowMsg停止了通话;标记名是创建的标签名,如标签或跨度。复制代码如下: //Create DOM函数createshowelement(current tid,elementid,style,showmsg,tagname) {if(!标记名)标记名=' labelvar current DOM=document . getelementbyid(current tid);var showMsgDom=document . create element(标记名);//showmsgdom . SetAttribute(' style ',' color: ' textColor');if(style)showmsgdom . setattribute(' style ',style);showMsgDom.setAttribute('id ',element id);showMsgDom.innerHTML=showMsgcurrent DOM . parent node . insert before(showMsgDom,current DOM . next sibling);}仅供交流。欢迎大家提意见,渴望有价值的意见。个人认为,即使写一个简单的脚本验证程序,也要尽可能遵循面向对象的思想,在可扩展性和效率上追求一个协调点,不会影响效率,同时让我们写的任何程序都有更高的可扩展性。这个想法并不难,但往往被很多初级程序员忽略。
版权声明:使用原生javascript创建通用表单验证——更敏锐地使用dom对象是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。