Home >Web Front-end >JS Tutorial >Learn jQuery from scratch (11) Practical form validation and auto-complete prompt plug-in_jquery
本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案, 即使你会使用jQuery也能在阅读中发现些许秘籍.
本文是介绍两个最常用的jQuery插件. 分别用于表单验证和自动完成提示(类似google suggest).
研究别人的作品真是一件花时间而且痛苦的过程. 当然也和本人英文不好有关. 总觉得控件作者写了很多文档但是都不够系统, 需要深入研究很多的实例后才能了解作者的思路.所以学习和研究一个插件需要很高成本, 如果发现了Bug并修复需要的成本也是未知数(本次我花了较少的时间解决了自动完成提示插件的一个中文bug, 但是如果复杂的bug就不会这么简单了.).
对于简单应用我首先推荐上文中的jQuery UI. 但是jQuery UI解决的问题有限. 使用jQuery插件是我们最后的一个好办法---还算是好办法, 起码比自己开发要好吧?
很多jQuery的插件编码异常优美, 看一看艺龙首页现在的城市输入框控件, 除了需要为输入框手工添加很多很多属性(onkeyup, onkeydown等等), 而且还不够通用, 占用服务器资源和网络资源.但是当初也是花费了很久的时间完成的作品.
站在巨人的肩膀上, 让我感觉写脚本和写设计C#程序一样, 都有高度和深度可以挖掘. 除了使用作者开发好的功能, 还可以学习如何开发和封装javascript控件. 看过优秀的jQuery插件作者的代码和设计思想后, 常常自叹设计水平差距居然如此之大, 增加自认为脚本高手, 比较过后就是C#程序员和架构师之间的差距.
希望大家通过本章节介绍的两个插件, 除了学会如何使用, 还能够略微领悟到如何封装和设计javascript控件.
在提交表单前常要对用户输入进行校验.ASP.NET的验证控件就是用于此目的, 可以同时进行客户端和服务器端验证. 但是验证控件并没有被所有项目采用. 而且在MVC项目中经常使用自己的客户端验证框架.
在比较了若干表单验证插件后, 决定采用validate插件. 因为其使用简单并且灵活.
插件首页:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
插件文档:
http://docs.jquery.com/Plugins/Validation
配置说明:
http://docs.jquery.com/Plugins/Validation/validate#options
<span class="asp"><%@ Page Language="C#" %></span> <span class="kwrd"><!</SPAN><SPAN class=html>DOCTYPE</SPAN> <SPAN class=attr>html</SPAN> <SPAN class=attr>PUBLIC</SPAN> <SPAN class=kwrd>"-//W3C//DTD XHTML 1.0 Transitional//EN"</SPAN> <SPAN class=kwrd>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</SPAN><SPAN class=kwrd>></span> <span class="kwrd"><</SPAN><SPAN class=html>html</SPAN> <SPAN class=attr>xmlns</SPAN><SPAN class=kwrd>="http://www.w3.org/1999/xhtml"</SPAN><SPAN class=kwrd>></span> <span class="kwrd"><</SPAN><SPAN class=html>head</SPAN> <SPAN class=attr>id</SPAN><SPAN class=kwrd>="Head1"</SPAN> <SPAN class=attr>runat</SPAN><SPAN class=kwrd>="server"</SPAN><SPAN class=kwrd>></span> <span class="kwrd"><</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></span>jQuery PlugIn - 表单验证插件实例 Validate <span class="kwrd"></</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></span> <span class="rem"><!--black-tie,blitzer,blitzer,dot-luv,excite-bike,hot-sneaks,humanity,mint-choc,redmond,smoothness,south-street,start,swanky-purse,trontastic,ui-darkness,ui-lightness,vader--></span> <span class="kwrd"><</SPAN><SPAN class=html>link</SPAN> <SPAN class=attr>rel</SPAN><SPAN class=kwrd>="stylesheet"</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/css"</SPAN> <SPAN class=attr>href</SPAN><SPAN class=kwrd>="<%=WebConfig.ResourceServer +"</SPAN>/<SPAN class=attr>JsLib</SPAN>/<SPAN class=attr>jquery</SPAN>/<SPAN class=attr>themes</SPAN>/<SPAN class=attr>redmond</SPAN>/<SPAN class=attr>style</SPAN>.<SPAN class=attr>css</SPAN><SPAN class=kwrd>"%>"</span> <span class="kwrd">/></span> <span class="kwrd"><</SPAN><SPAN class=html>script</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/javascript"</SPAN> <SPAN class=attr>src</SPAN><SPAN class=kwrd>="<% =WebConfig.ResourceServer %>/JsLib/jquery/jquery-min-lastest.js"</span><span class="kwrd">></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span> <script type=<SPAN class=str>"text/javascript"</SPAN> src=<SPAN class=str>"<% =WebConfig.ResourceServer %>/JsLib/jquery/ui/jquery-ui-all-min-lastest.js"></script> <script type=<SPAN class=str>"text/javascript"</SPAN> src=<SPAN class=str>"<% =WebConfig.ResourceServer %>/JsLib/jquery/plugin/jquery.validate/jquery.validate.min.js"></script> <script type=<SPAN class=str>"text/javascript"</SPAN> src=<SPAN class=str>"<% =WebConfig.ResourceServer %>/JsLib/jquery/plugin/jquery.validate/localization/messages_cn.js"></script> <% <SPAN class=kwrd>if</SPAN> (<SPAN class=kwrd>false</SPAN>) {%><script src=<SPAN class=str>"~/js/jquery-vsdoc-lastest.js"</SPAN> type=<SPAN class=str>"text/javascript"</SPAN>></script> <% }%> <script type=<SPAN class=str>"text/javascript"</SPAN>> <span class="rem">/*========== 必须放在头部加载的语句块. 尽量避免使用 ==========*/</span> <span class="kwrd"></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span> <style type=<SPAN class=str>"text/css"</SPAN>> body { font-size:12px; } <span class="rem">/* form中显示文字的label */</span> .slabel { width:100px; display: -moz-inline-box; line-height: 1.8; display: inline-block; text-align:right; } <span class="rem">/* 出错样式 */</span> input.error, textarea.error { border: solid 1px #CD0A0A; } label.error { color:#CD0A0A; margin-left:5px; } <span class="rem">/* 深红色文字 */</span> .textred { color:#CD0A0A; } </style> </head> <body> <form id=<SPAN class=str>"commentForm"</SPAN> method=<SPAN class=str>"get"</SPAN> action=<SPAN class=str>""</SPAN>> <fieldset style=<SPAN class=str>"width:500px;"</SPAN>><legend>表单验证</legend> <p><label <SPAN class=kwrd>for</SPAN>=<SPAN class=str>"cname"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"slabel"</SPAN>><em <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"textred"</SPAN>>*</em> 姓名:</label> <input id=<SPAN class=str>"cname"</SPAN> name=<SPAN class=str>"name"</SPAN> size=<SPAN class=str>"25"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"required"</SPAN> minlength=<SPAN class=str>"2"</SPAN> /> </p> <p><label <SPAN class=kwrd>for</SPAN>=<SPAN class=str>"cemail"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"slabel"</SPAN>><em <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"textred"</SPAN>>*</em> E-Mail:</label> <input id=<SPAN class=str>"cemail"</SPAN> name=<SPAN class=str>"email"</SPAN> size=<SPAN class=str>"25"</SPAN>/> </p> <p><label <SPAN class=kwrd>for</SPAN>=<SPAN class=str>"curl"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"slabel"</SPAN>>网址:</label> <input id=<SPAN class=str>"curl"</SPAN> name=<SPAN class=str>"url"</SPAN> size=<SPAN class=str>"25"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"url"</SPAN> value=<SPAN class=str>""</SPAN> /> </p> <p><label <SPAN class=kwrd>for</SPAN>=<SPAN class=str>"ccomment"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"slabel"</SPAN>><em <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"textred"</SPAN>>*</em> 内容:</label> <textarea rows=<SPAN class=str>"2"</SPAN> id=<SPAN class=str>"ccomment"</SPAN> name=<SPAN class=str>"comment"</SPAN> cols=<SPAN class=str>"20"</SPAN> <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"required"</SPAN> style=<SPAN class=str>"height:80px;"</SPAN>></textarea> </p> <p style=<SPAN class=str>"text-align:center;"</SPAN>> <input <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"submit"</SPAN> type=<SPAN class=str>"submit"</SPAN> value=<SPAN class=str>"提交"</SPAN> /> </p> </fieldset> </form> <script type=<SPAN class=str>"text/javascript"</SPAN>> <span class="rem">/*==========用户自定义方法==========*/</span> <span class="rem">/*==========事件绑定==========*/</span> $(<span class="kwrd">function</span>() { }); <span class="rem">/*==========加载时执行的语句==========*/</span> $(<span class="kwrd">function</span>() { $(<span class="str">"#commentForm"</span>).validate( { errorClass: <span class="str">"error"</span>, submitHandler: <span class="kwrd">function</span>(form) { <span class="rem">//如果想提交表单, 需要使用form.submit()而不要使用$(form).submit()</span> alert(<span class="str">"submitted!"</span>); }, rules: { <span class="rem">//为name为email的控件添加两个验证方法:required()和email()</span> email: { required: <span class="kwrd">true</span>, email: <span class="kwrd">true</span> } }, messages: { <span class="rem">//为name为email的控件的required()和email()验证方法设置验证失败的消息内容</span> email: {required:<span class="str">"需要输入电子邮箱"</span>, email:<span class="str">"电子邮箱格式不正确"</span>} } }); }); <span class="kwrd"></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span> <span class="kwrd"></</SPAN><SPAN class=html>body</SPAN><SPAN class=kwrd>></span> <span class="kwrd"></</SPAN><SPAN class=html>html</SPAN><SPAN class=kwrd>></span>
验证方法是验证某一个控件是否满足某些规则的方法, 返回一个boolean值. 比如email( ) 方法验证内容是否符合email格式, 符合则返回true. 下面是类库中email方法的源代码:
<span class="rem">// http://docs.jquery.com/Plugins/Validation/Methods/email</span> email: <span class="kwrd">function</span>(value, element) { <span class="rem">// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/</span> <span class="kwrd">return</span> <span class="kwrd">this</span>.optional(element) || /^((([a-z]|\d|[!#\$%&<span class="str">'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'</span>\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value); },
我们在:
http://docs.jquery.com/Plugins/Validation
中的 List of built-in Validation methods 一节中列出了所有内置的验证方法. 同时插件还提供了additional-methods.js 文件, 里面包含了更多的验证方法, 引入后既可启用.
验证消息就是验证方法失败后显示的文字内容. 验证消息一定关联在某一个验证方法上, 并且全局的验证消息保存在jQuery.validator.messages 属性中.
默认的validate类库自带英文验证消息:
messages: { required: <span class="str">"This field is required."</span>, <span class="rem">//... </span> });
上面说明当required验证方法验证失败是, 显示"This field is required."这条消息.
在下载文件的localization文件夹中, 包含了各国语言的基本验证消息, 如同本实例一样引入不同的语言文件即可实现语言切换:
<span class="kwrd"><</SPAN><SPAN class=html>script</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/javascript"</SPAN> <SPAN class=attr>src</SPAN><SPAN class=kwrd>="<% =WebConfig.ResourceServer %>/JsLib/jquery/plugin/jquery.validate/localization/messages_cn.js"</span><span class="kwrd">></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span>
语言文件的内容举例:
jQuery.extend(jQuery.validator.messages, { required: <span class="str">"必选字段"</span>, <span class="rem">//...</span> });<style type="text/css">.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } </style>
现在必填项的问题提示就变成了中文.
除了全局默认的验证消息, 也可以为某一个表单元素设置特有的验证消息, 比如本文实例中, 为email元素设置了特有的验证消息:
messages: { <span class="rem">//为name为email的控件的required()和email()验证方法设置验证失败的消息内容</span> email: {required:<span class="str">"需要输入电子邮箱"</span>, email:<span class="str">"电子邮箱格式不正确"</span>}
options的messages属性可以针对某一个表单元素设置验证消息, 第一个email表示email元素, 值是一个集合, required就表示required验证函数, 第二个email表示是email验证函数.
验证规则就是这样的语意语句: 在元素A上, 使用 验证方法A 和 验证方法B 进行验证.
验证规则将元素与验证方法关联起来, 因为验证方法同时也关联了验证消息, 所以元素与消息也关联了起来.
为一个元素添加验证规则有多种方式.
本实例的"姓名"元素使用了CSS样式规则和元素属性规则:
<span class="kwrd"><</SPAN><SPAN class=html>input</SPAN> <SPAN class=attr>id</SPAN><SPAN class=kwrd>="cname"</SPAN> <SPAN class=attr>name</SPAN><SPAN class=kwrd>="name"</SPAN> <SPAN class=attr>size</SPAN><SPAN class=kwrd>="25"</SPAN> <SPAN class=attr>class</SPAN><SPAN class=kwrd>="required"</SPAN> <SPAN class=attr>minlength</SPAN><SPAN class=kwrd>="2"</SPAN> <SPAN class=kwrd>/></span>
class元素属性设置元素的CSS样式类, 因为样式类中添加了required类, 所以会和required()验证函数关联. 这种规则叫做CSS样式规则.
minlength元素属性也会自动和minlength()验证函数关联, 这种规则叫做元素属性规则.
另外还可以通过编程的方式进行关联:
rules: { <span class="rem">//为name为email的控件添加两个验证方法:required()和email()</span> email: { required: <span class="kwrd">true</span>, email: <span class="kwrd">true</span> } },
上面的语句表名为email表单对象添加了required()和email()验证函数.
默认情况下, 当验证函数失败时表单不会提交.
但是可以通过添加class="cancel"的方式让提交按钮跳过验证:
<span class="kwrd"><</SPAN><SPAN class=html>input</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="submit"</SPAN> <SPAN class=attr>class</SPAN><SPAN class=kwrd>="cancel"</SPAN> <SPAN class=attr>name</SPAN><SPAN class=kwrd>="cancel"</SPAN> <SPAN class=attr>value</SPAN><SPAN class=kwrd>="Cancel"</SPAN> <SPAN class=kwrd>/></span>
当表单提交时, 会触发options中submitHandler属性设置的函数:
submitHandler: <span class="kwrd">function</span>(form) { <span class="rem">//如果想提交表单, 需要使用form.submit()而不要使用$(form).submit()</span> alert(<span class="str">"submitted!"</span>); },
此函数的签名同上. 我们可以在这个函数中, 编写在表单提交前需要处理的业务逻辑.
需要注意当最后以编程的方式提交表单时, 一定不要使用jQuery对象的submit()方法, 因为此方法会触发表单验证,并且再次调用submitHandler设置的函数, 会导致递归调用.
此函数的参数form就是表单对象, 用途就是不进行验证提交表单:form.submit()
在开发阶段我们通常不希望表单被真正提交, 虽然可以通过本实例中重写submitHandler函数来实现, 但是还有更好的方式, 我们可以在submitHandler函数完成正式提交的逻辑, 然后通过设置options的debug属性, 来达到即使验证通过也不会提交表单的目的:
$(<span class="str">".selector"</span>).validate({ debug: <span class="kwrd">true</span> })
有时会在一个页面上出现多个Form, 因为validate控件是针对form对象进行包装的, 所以我们可以控制哪些form对象需要验证.
同时为了方便一次设置页面上所有的应用了validate控件的form对象, 提供了 jQuery.validator.setDefaults 函数让我们可以一次设置所有的默认值:
jQuery.validator.setDefaults({ debug: <span class="kwrd">true</span> });
autocomplete插件能帮助我们实现类似于Google Suggest的效果:
插件首页:
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
插件文档:
http://docs.jquery.com/Plugins/Autocomplete
配置说明:
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions
本实例演示的是使用autocomplete完成对输入城市的自动提示效果,如图:
实例代码:
<span class="asp"><%@ Page Language="C#" %></span> <span class="kwrd"><!</SPAN><SPAN class=html>DOCTYPE</SPAN> <SPAN class=attr>html</SPAN> <SPAN class=attr>PUBLIC</SPAN> <SPAN class=kwrd>"-//W3C//DTD XHTML 1.0 Transitional//EN"</SPAN> <SPAN class=kwrd>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</SPAN><SPAN class=kwrd>></span> <span class="kwrd"><</SPAN><SPAN class=html>html</SPAN> <SPAN class=attr>xmlns</SPAN><SPAN class=kwrd>="http://www.w3.org/1999/xhtml"</SPAN><SPAN class=kwrd>></span> <span class="kwrd"><</SPAN><SPAN class=html>head</SPAN> <SPAN class=attr>id</SPAN><SPAN class=kwrd>="Head1"</SPAN> <SPAN class=attr>runat</SPAN><SPAN class=kwrd>="server"</SPAN><SPAN class=kwrd>></span> <span class="kwrd"><</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></span>jQuery PlugIn - 自动完成插件实例 AutoComplete <span class="kwrd"></</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></span> <span class="rem"><!--black-tie,blitzer,blitzer,dot-luv,excite-bike,hot-sneaks,humanity,mint-choc,redmond,smoothness,south-street,start,swanky-purse,trontastic,ui-darkness,ui-lightness,vader--></span> <span class="kwrd"><</SPAN><SPAN class=html>link</SPAN> <SPAN class=attr>rel</SPAN><SPAN class=kwrd>="stylesheet"</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/css"</SPAN> <SPAN class=attr>href</SPAN><SPAN class=kwrd>="<%=WebConfig.ResourceServer +"</SPAN>/<SPAN class=attr>JsLib</SPAN>/<SPAN class=attr>jquery</SPAN>/<SPAN class=attr>themes</SPAN>/<SPAN class=attr>redmond</SPAN>/<SPAN class=attr>style</SPAN>.<SPAN class=attr>css</SPAN><SPAN class=kwrd>"%>"</span> <span class="kwrd">/></span> <span class="kwrd"><</SPAN><SPAN class=html>link</SPAN> <SPAN class=attr>rel</SPAN><SPAN class=kwrd>="stylesheet"</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/css"</SPAN> <SPAN class=attr>href</SPAN><SPAN class=kwrd>="<%=WebConfig.ResourceServer +"</SPAN>/<SPAN class=attr>JsLib</SPAN>/<SPAN class=attr>jquery</SPAN>/<SPAN class=attr>plugin</SPAN>/<SPAN class=attr>jquery</SPAN>.<SPAN class=attr>autocomplete</SPAN>/<SPAN class=attr>jquery</SPAN>.<SPAN class=attr>autocomplete</SPAN>.<SPAN class=attr>css</SPAN><SPAN class=kwrd>"%>"</span> <span class="kwrd">/></span> <span class="kwrd"><</SPAN><SPAN class=html>script</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/javascript"</SPAN> <SPAN class=attr>src</SPAN><SPAN class=kwrd>="<% =WebConfig.ResourceServer %>/JsLib/jquery/jquery-min-lastest.js"</span><span class="kwrd">></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span> <script type=<SPAN class=str>"text/javascript"</SPAN> src=<SPAN class=str>"<% =WebConfig.ResourceServer %>/JsLib/jquery/ui/jquery-ui-all-min-lastest.js"></script> <script type=<SPAN class=str>"text/javascript"</SPAN> src=<SPAN class=str>"<% =WebConfig.ResourceServer %>/JsLib/jquery/plugin/jquery.autocomplete/jquery.autocomplete.min.js"></script> <% <SPAN class=kwrd>if</SPAN> (<SPAN class=kwrd>false</SPAN>) {%><script src=<SPAN class=str>"~/js/jquery-vsdoc-lastest.js"</SPAN> type=<SPAN class=str>"text/javascript"</SPAN>></script> <% }%> <script type=<SPAN class=str>"text/javascript"</SPAN>> <span class="rem">/*========== 必须放在头部加载的语句块. 尽量避免使用 ==========*/</span> <span class="kwrd"></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span> <style type=<SPAN class=str>"text/css"</SPAN>> body { font-size: 12px; } .formLabel{<span class="kwrd">float</span>: left; width: 150px; text-align:right;} .formInput{<span class="kwrd">float</span>: left;} </style> </head> <body> <!-- Demo. 应用AutoComplete插件 --> <div <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"ui-widget ui-widget-content ui-corner-all"</SPAN> style=<SPAN class=str>"width: 700px; padding: 5px;"</SPAN>> <h3> Demo. 应用AutoComplete插件 </h3> <br style=<SPAN class=str>"clear: both"</SPAN> /> <div <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"formLabel"</SPAN>> <label <SPAN class=kwrd>for</SPAN>=<SPAN class=str>"inputCityName"</SPAN>>请输入城市拼音和汉字:</label> </div> <div <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"formInput"</SPAN>> <input id=<SPAN class=str>"inputCityName"</SPAN> name=<SPAN class=str>"inputCityName"</SPAN> type=<SPAN class=str>"text"</SPAN> /> </div> <br style=<SPAN class=str>"clear:both"</SPAN> /> <br style=<SPAN class=str>"clear: both"</SPAN> /> <div <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"formLabel"</SPAN>> <label <SPAN class=kwrd>for</SPAN>=<SPAN class=str>"inputCityName"</SPAN>>城市ID:</label></div> <div <SPAN class=kwrd>class</SPAN>=<SPAN class=str>"formInput"</SPAN>> <input id=<SPAN class=str>"inputCityId"</SPAN> name=<SPAN class=str>"inputCityId"</SPAN> type=<SPAN class=str>"text"</SPAN> /></div> <br style=<SPAN class=str>"clear: both"</SPAN> /> <br style=<SPAN class=str>"clear: both"</SPAN> /> </div> <script type=<SPAN class=str>"text/javascript"</SPAN>> <span class="rem">/*==========用户自定义方法==========*/</span> <span class="rem">//城市数据</span> <span class="kwrd">var</span> cityList; <span class="rem">//autocomplete选项</span> <span class="kwrd">var</span> options = { minChars: 1, max: 500, width: 250, matchContains: <span class="kwrd">true</span>, formatItem: <span class="kwrd">function</span>(row, i, max) { <span class="kwrd">return</span> i + <span class="str">"/"</span> + max + <span class="str">": \""</span> + row.CityNameEn + <span class="str">"\" ["</span> + row.CityName + <span class="str">"]"</span>; }, formatMatch: <span class="kwrd">function</span>(row, i, max) { <span class="kwrd">return</span> row.CityNameEn + <span class="str">" "</span> + row.CityName; }, formatResult: <span class="kwrd">function</span>(row) { <span class="kwrd">return</span> row.CityName; } }; <span class="rem">//autocomplete初始化函数</span> <span class="kwrd">function</span> initAutoComplete(data) { cityList = data; $(<span class="str">"#inputCityName"</span>).autocomplete(cityList, options); $(<span class="str">"#inputCityName"</span>).result(<span class="kwrd">function</span>(<span class="kwrd">event</span>, data, formatted) { $(<span class="str">"#inputCityId"</span>).val(data.ElongCityId); }); } <span class="rem">/*==========事件绑定==========*/</span> $(<span class="kwrd">function</span>() { }); <span class="rem">/*==========加载时执行的语句==========*/</span> $(<span class="kwrd">function</span>() { <span class="rem">//加载城市数据, 并在回调函数中用返回的数据初始化autocomplete</span> $.getJSON(<span class="str">"cityinfo.htm"</span>, <span class="kwrd">null</span>, initAutoComplete) }); <span class="kwrd"></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></span> <span class="kwrd"></</SPAN><SPAN class=html>body</SPAN><SPAN class=kwrd>></span> <span class="kwrd"></</SPAN><SPAN class=html>html</SPAN><SPAN class=kwrd>></span>
首先要准备实现自动建议的数据源. 本实例是通过发送Ajax请求获取JSON对象. autocomplete()方法支持两个参数, 第一个是data, 第二个是options.
其中data参数可以使本实例中的一个数据变量, 也可以是一个url. 如果是url则会每次都调用Ajax请求获取数据.
为了效率我倾向于在数据量允许的情况下, 在页面加载后使用Ajax获取全部的数据, 然后使用传递数据变量给autocomplete组件. 如实例中所示. 除非数据特别巨大无法再客户端加载, 则只能每次都使用发送Ajax请求从服务器端获取部分数据. 但是这会对服务器造成负担.
虽然options是可选项, 但是对于我们的数据源cityList是一个多属性对象, 所以必须设置下面几个关键的配置项后才能够使用:
对匹配的每一行数据使用此函数格式化, 返回值是显示给用户的数据内容.
函数签名:
function(row, rowNum, rowCount, searchItem)
参数说明:
row: 当前行. the results row,
rowNum: 当前行号,从1开始.(注意不是索引,索引从0开始) the position of the row in the list of results (starting at 1),
rowCount: 总的行号 the number of items in the list of results
searchItem: 查询使用的数据, 即formatMatch函数返回的数据格式的内容. 我们在formatMatch函数中会设置程序内部搜索时使用的数据格式,这个格式和给用户展示的数据是不同的.
对每一行数据使用此函数格式化需要查询的数据格式. 返回值是给内部搜索算法使用的. 实例中用户看到的匹配结果是formatItem中设置的格式, 但是程序内部其实只搜索城市的英文和中文名称, 搜索数据在formatMatch中定义:
<span class="kwrd">return</span> row.CityNameEn + <span class="str">" "</span> + row.CityName;
函数签名:
function(row, rowNum, rowCount,)
参数说明同上
此函数是用户选中后返回的数据格式. 比如实例中只返回城市名给input控件:
<span class="kwrd">return</span> row.CityName;
函数签名:
function(row, rowNum, rowCount,)
参数说明同上
上面3个函数无法实现这类要求: 虽然只返回城市名称, 但是查询时使用城市ID, 选中一个城市后需要将城市ID存储在一个隐藏域中.
所以autocomplete控件提供了result事件函数, 此事件会在用户选中某一项后触发:
$(<span class="str">"#inputCityName"</span>).result(<span class="kwrd">function</span>(<span class="kwrd">event</span>, data, formatted) { $(<span class="str">"#inputCityId"</span>).val(data.ElongCityId); });
函数签名:
function(event, data, formatted)
参数列表:
Result 이벤트는 바인딩된 이벤트 핸들러에 세 가지 매개변수를 전달합니다.
이벤트: 이벤트 개체입니다. event.type이 결과입니다.
데이터: 선택한 데이터 행.
formatd: 공식적인 설명은 formatResult 함수에서 반환된 값이어야 하지만 실험 결과는 formatMatch에서 반환된 값입니다. 이 예에서는 "Beijing Beijing"입니다.
현재 버전의 자동완성 컨트롤에는 중국어 검색에 버그가 있습니다. 그 이유는 검색 이벤트가 keydown 이벤트에 바인딩되어 있기 때문입니다. 중국어 입력 방법을 사용하여 "北"이라는 단어를 입력하면 프롬프트가 표시되지 않습니다. . 중국어에 대한 지능형 프롬프트 검색을 완료하려면 keydown 이벤트를 keyup 이벤트로 수정해야 합니다. 또한 검색 형식이 다음과 같기 때문에 주로 "matchContains" 구성 항목을 "true"로 설정해야 합니다. "Beijing Beijing"이며 기본적으로 시작 문자만 일치합니다.
자세한 구성 항목은 공식 문서를 참조하세요.
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions
위에 소개된 autocomplete() 및 result() 함수 외에도 다음과 같은 함수도 있습니다.
검색( ) : 검색 이벤트 활성화
flushCache( ) : 캐시 지우기
setOptions( options ) : 구성 항목 설정
이 글에서는 양식 유효성 검사 플러그인과 자동 완성 플러그인을 자세히 소개합니다. 현재 수많은 플러그인 애플리케이션, 수천 개의 플러그인 목록을 검색할 수 있지만 자세한 사용 설명서는 찾을 수 없습니다. 플러그인은 사용하기 쉽지만 실제로 적용하기가 쉽지 않습니다. 기본 사용법을 배우기 위해 영어 설명서를 읽는 것 외에도 각 매개 변수의 역할과 사용 방법을 이해하는 데 시간이 오래 걸립니다. 게다가 2차 개발도 상대적으로 어렵고, 플러그인에 핵심 코드가 많아 설명도 없고 복잡하며, 논리적인 관계를 찾는 데도 많은 시간과 노력이 소요됩니다. . 본 글에 소개된 두 가지 플러그인에 대한 자세한 내용은 공식 문서를 참고하시기 바라며, 주소는 처음에 모두 제공됩니다.
다음 글에서는 jQuery 기술과 자바스크립트에 필요한 지식을 먼저 설명하기로 했습니다. 우리는 커스텀 플러그인을 개발하는 일이 거의 없기 때문에 플러그인 개발에 대해서는 마지막에 다루겠습니다.
이 장의 코드를 다운로드하세요:http://xiazai.jb51.net/201101/yuanma/Code-jQueryStudy-11.rar