jquery autocomplete 自动填充下拉框的使用之自定义数据显示

官方的介绍地址为

http://jqueryui.com/autocomplete/

本文对于简单的使用不做介绍,仅仅介绍自定义数据结构如何进行显示,在官方的demo中也有(http://www.jqueryui.org.cn/demo/5663.html),代码如下:

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>jQuery UI 自动完成(Autocomplete) - 自定义数据并显示</title>
      
      <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
 
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
     
      <style>
      #project-label {
        display: block;
        font-weight: bold;
        margin-bottom: 1em;
      }
      #project-icon {
        float: left;
        height: 32px;
        width: 32px;
      }
      #project-description {
        margin: 0;
        padding: 0;
      }
      </style>
      <script>
      $(function() {
        var projects = [
          {
            value: "jquery",
            label: "jQuery",
            desc: "the write less, do more, JavaScript library",
            icon: "jquery_32x32.png"
          },
          {
            value: "jquery-ui",
            label: "jQuery UI",
            desc: "the official user interface library for jQuery",
            icon: "jqueryui_32x32.png"
          },
          {
            value: "sizzlejs",
            label: "Sizzle JS",
            desc: "a pure-JavaScript CSS selector engine",
            icon: "sizzlejs_32x32.png"
          }
        ];
     
        $( "#project" ).autocomplete({
          minLength: 0,
          source: projects,
          focus: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            return false;
          },
          select: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            $( "#project-id" ).val( ui.item.value );
            $( "#project-description" ).html( ui.item.desc );
            $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
     
            return false;
          }
        })
        .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
          return $( "<li>" )
            .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
            .appendTo( ul );
        };
      });
      </script>
    </head>
    <body>
     
    <div id="project-label">选择一个项目(请键入 "j"):</div>
    <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="">
    <input id="project">
    <input type="hidden" id="project-id">
    <p id="project-description"></p>
     
     
    </body>
    </html>

运行这个例子发现没有问题。但是我们的数据不可能json对象中的key值就这集中固定的,确切的说必须包含value或label。为什么呢?请看jquer-ui中的匹配过滤

_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax( {
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response( [] );
					}
				} );
			};
		} else {
			this.source = this.options.source;
		}
	},

对于[{k:v,k:v,......},{k:v,k:v,......},{},.....] 这样的数据,会走第一个if分支,其中的代码

response( $.ui.autocomplete.filter( array, request.term ) );

就是用来进行匹配的。

这个匹配最终会调用如下的部分:

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		} );
	}
} );

看到这里你应该明白了,其实就是把你输入的内容(term就是输入的内容)和数组集合中的label或者value这两个key所代表的的值 或者 数组本身 进行比较 (按照正则表达式escapeRegex所定义) 来决定是否应该显示。

看到这里,我想你就能知道如何适应自己json对象中的key值了。

有两种方式:

我们使用的json对象r

[
{
    "deviceName": "computer",
    "methodName": "download"
},
{
    "deviceName": "printer",
    "methodName": "test"
},
{
    "deviceName": "server",
    "methodName": "job"
},
{
    "deviceName": "desk",
    "methodName": "add"
},
{
    "deviceName": "chair",
    "methodName": "update"
},
}
】

需要下拉框的input,其id是inputid

<input id="inputid" type="text" name="beanName"  class="form-control">

第一种: 我们把自己的key值和label或value做一个映射,然后交给source去进行比较。

这种方法是最简单的,我们对source定义如下
 

$('#inputid').autocomplete({
          source:  function( request, response ) {   
            //r 是我们自己的json对象数组
            response( $.map( r, function( item ) {
                                  return {
                                  //我们自己根据需要把对象中的属性值和label value做一个映射
                                    label: item.beanName,
                                    value: item.methodName+":"+item.params,
                                  }
                                }));
                    },
//由于我们做了一个映射,所以以下中所有的item就只能具有label和value了,不再有我们自己对象的key值
           focus: function( event, ui ) {
 		        $( "#inputid" ).val( ui.item.label );
 		        return false;
 		      },
 		      select: function( event, ui ) {
 		        $( "#inputid" ).val( ui.item.label );
 		       
 		 
 		        return false;
 		      }
 		    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
    	      return $( "<li>" )
    	          .append( "<a>" + item.label + "<br>" + item.value + "</a>" )
    	        .appendTo( ul );
    	    };

上面代码已经很详细了,不在说明了,唯一说的是在给value和label做映射代码里,那个deviceName  methodName是我们以前的json对象的key。

第二种方法就是,我们自己定义匹配规则,然后把结果给source

$('#inputid').autocomplete({
    		source: function( request, response ) {
            	        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            	        //r是我们需要显示的数据,这里要自定义匹配规则
            	        response( $.grep( r, function( value ) {
                            //匹配的规则让然是官方的正则规则,只不过我们拿json对象中的beanName和输入的内容进行匹配比较
            	          value = value.beanName;
            	          return matcher.test( value );
            	        }) );
            	      },
    		minLength: 0,    	      
    		focus: function( event, ui ) {
     		        $( "#inputid" ).val( ui.item.beanName);
     		        return false;
     		      },
     		      select: function( event, ui ) {
     		        $( "#inputid" ).val( ui.item.beanName);   		 
     		        return false;
     		      }
 		    }) 		    
 		    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
    	      return $( "<li>" )
    	          .append( "<a>" + item.beanName + "</a>" )
    	        .appendTo( ul );
    	    };

猜你喜欢

转载自blog.csdn.net/feixiangsmile/article/details/82961120
今日推荐