ゼロから学ぶjQuery (11) 実践的なフォーム検証とオートコンプリートプロンプト plug-in_jquery

WBOY
リリース: 2016-05-16 18:10:22
オリジナル
904 人が閲覧しました

一.摘要

本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案,  即使你会使用jQuery也能在阅读中发现些许秘籍.

本文是介绍两个最常用的jQuery插件. 分别用于表单验证和自动完成提示(类似google suggest).

二.前言

研究别人的作品真是一件花时间而且痛苦的过程. 当然也和本人英文不好有关. 总觉得控件作者写了很多文档但是都不够系统, 需要深入研究很多的实例后才能了解作者的思路.所以学习和研究一个插件需要很高成本, 如果发现了Bug并修复需要的成本也是未知数(本次我花了较少的时间解决了自动完成提示插件的一个中文bug, 但是如果复杂的bug就不会这么简单了.).

对于简单应用我首先推荐上文中的jQuery UI. 但是jQuery UI解决的问题有限. 使用jQuery插件是我们最后的一个好办法---还算是好办法, 起码比自己开发要好吧?

很多jQuery的插件编码异常优美, 看一看艺龙首页现在的城市输入框控件, 除了需要为输入框手工添加很多很多属性(onkeyup, onkeydown等等), 而且还不够通用, 占用服务器资源和网络资源.但是当初也是花费了很久的时间完成的作品.

站在巨人的肩膀上, 让我感觉写脚本和写设计C#程序一样, 都有高度和深度可以挖掘. 除了使用作者开发好的功能, 还可以学习如何开发和封装javascript控件. 看过优秀的jQuery插件作者的代码和设计思想后, 常常自叹设计水平差距居然如此之大, 增加自认为脚本高手, 比较过后就是C#程序员和架构师之间的差距.

希望大家通过本章节介绍的两个插件, 除了学会如何使用,  还能够略微领悟到如何封装和设计javascript控件.

 

三.表单验证插件 validate

在提交表单前常要对用户输入进行校验.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

1.应用实例

实例效果:

image

实例代码:

<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>
ログイン後にコピー

 

2. 实例讲解

(1) 验证方法

验证方法是验证某一个控件是否满足某些规则的方法, 返回一个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 文件, 里面包含了更多的验证方法, 引入后既可启用.

(2) 验证消息

验证消息就是验证方法失败后显示的文字内容. 验证消息一定关联在某一个验证方法上, 并且全局的验证消息保存在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验证函数.

(3)验证规则

验证规则就是这样的语意语句: 在元素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()验证函数.

(4)  表单提交

默认情况下, 当验证函数失败时表单不会提交.

但是可以通过添加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()

(5) DEBUG模式

在开发阶段我们通常不希望表单被真正提交,  虽然可以通过本实例中重写submitHandler函数来实现, 但是还有更好的方式, 我们可以在submitHandler函数完成正式提交的逻辑, 然后通过设置options的debug属性, 来达到即使验证通过也不会提交表单的目的:

$(<span class="str">".selector"</span>).validate({
  debug: <span class="kwrd">true</span>
})
ログイン後にコピー

(6) 多表单验证

有时会在一个页面上出现多个Form, 因为validate控件是针对form对象进行包装的, 所以我们可以控制哪些form对象需要验证.

同时为了方便一次设置页面上所有的应用了validate控件的form对象,  提供了 jQuery.validator.setDefaults 函数让我们可以一次设置所有的默认值:

jQuery.validator.setDefaults({ 
  debug: <span class="kwrd">true</span> 
});
ログイン後にコピー

 

 

四.自动完成插件 autocomplete

autocomplete插件能帮助我们实现类似于Google Suggest的效果:

image

插件首页:

http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

插件文档:

http://docs.jquery.com/Plugins/Autocomplete

配置说明:

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions

1.应用实例

本实例演示的是使用autocomplete完成对输入城市的自动提示效果,如图:

image

实例代码:

<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>
ログイン後にコピー

 

2. 实例讲解

(1)准备数据源

首先要准备实现自动建议的数据源. 本实例是通过发送Ajax请求获取JSON对象. autocomplete()方法支持两个参数, 第一个是data, 第二个是options.

其中data参数可以使本实例中的一个数据变量, 也可以是一个url. 如果是url则会每次都调用Ajax请求获取数据.

为了效率我倾向于在数据量允许的情况下, 在页面加载后使用Ajax获取全部的数据, 然后使用传递数据变量给autocomplete组件. 如实例中所示. 除非数据特别巨大无法再客户端加载,  则只能每次都使用发送Ajax请求从服务器端获取部分数据. 但是这会对服务器造成负担.

(2) 设置关键函数

虽然options是可选项, 但是对于我们的数据源cityList是一个多属性对象, 所以必须设置下面几个关键的配置项后才能够使用:

formatItem

对匹配的每一行数据使用此函数格式化, 返回值是显示给用户的数据内容.

函数签名:

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函数中会设置程序内部搜索时使用的数据格式,这个格式和给用户展示的数据是不同的.

formatMatch

对每一行数据使用此函数格式化需要查询的数据格式. 返回值是给内部搜索算法使用的. 实例中用户看到的匹配结果是formatItem中设置的格式, 但是程序内部其实只搜索城市的英文和中文名称, 搜索数据在formatMatch中定义:

<span class="kwrd">return</span> row.CityNameEn + <span class="str">" "</span> + row.CityName;
ログイン後にコピー


函数签名:

function(row, rowNum, rowCount,)

参数说明同上

formatResult

此函数是用户选中后返回的数据格式. 比如实例中只返回城市名给input控件:

<span class="kwrd">return</span> row.CityName;
ログイン後にコピー


函数签名:

function(row, rowNum, rowCount,)

参数说明同上

(3) 为控件添加Result事件函数

上面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)

参数列表:

The Result event will pass three parameters to the bound event handler:

event: event object. event.type is result.

data: selected data row.

formatted: Although the official explanation should be the value returned by the formatResult function, the experimental result is the value returned by formatMatch. In this example: "Beijing Beijing".

(4) Match Chinese

The current version of the autocomplete control has a bug in Chinese search. The reason is that its search event is bound to the keydown event. When the Chinese input method is used to input the word "北", there is no prompt. I made modifications to the original library. Modify the keydown event to the keyup event to complete the intelligent prompt search for Chinese. In addition, you mainly need to set the "matchContains" configuration item to "true", because our search format is "Beijing Beijing", and by default only the beginning characters are matched.

(5) More configuration items

For more configuration items, please refer to the official documentation:

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions

(6) More events

In addition to the autocomplete() and result() functions introduced above, there are also the following functions:

search( ) : Activate search event

flushCache( ) : Clear cache

setOptions( options ) : Set configuration items

5. Summary

This article introduces the form validation plug-in and the auto-complete plug-in in detail. Currently, you can search for many plug-in applications, or thousands of plug-in lists, but you cannot find detailed usage documentation. The plug-in is simple to use but truly flexible. It is not easy to apply. In addition to reading the English documentation to learn the basic usage, it also takes a long time to understand the role of each parameter and how to use it together. Moreover, it is relatively difficult to do secondary development on it, and the plug-in has a lot of core code. There are no comments and it is complicated, and it takes a lot of time and effort to find logical relationships. For more details about the two plug-ins introduced in this article, please refer to the official documents, and the addresses are provided for everyone at the beginning.

In the following articles, I decided to explain jQuery skills and necessary knowledge of javascript first. We rarely develop custom plug-ins, so we will put the development of plug-ins at the end.

Download the code for this chapter:http://xiazai.jb51.net/201101/yuanma/Code-jQueryStudy-11.rar

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート