$('#email').autocomplete({ delay:0, autoFocus:true, source:function(request,response){ var hosts = ['qq.com','163.com','263.com','gmail.com','sina.com.cn'], term = request.term,//获取用户输入内容 name = term,//邮箱的用户名 host = '',//邮箱的域名 ix = term.indexOf('@'),//@的位置 result = [];//最终呈现的邮箱列表 result.push(term); //当有@事重新分配用户名和域名 if(ix > -1){ name = term.slice(0,ix); host = term.slice(ix + 1); } if(name){ // var findedHosts = (host ? findedHosts = $.grep(hosts,function(value,index){ // return value.indexOf(host) > -1; // }) : hosts), // findedResult = $.map(findedHosts, function(value,index) { // return name + '@' + value; // }); //如果用户已经输入@和后面的域名 //那么就找到相关的域名提示,比如sfsdf@.1就提示sfsdf@.163.com //如果没输入都提示 var findedHosts = []; if(host){ findedHosts = $.grep(hosts,function(value,index){ return value.indexOf(host) > -1; }); }else{ findedHosts = hosts; } var findedResult = $.map(findedHosts, function(value,index) { return name + '@' + value; }); result = result.concat(findedResult); } response(result); }, });
另:$.grep()工具函数回调事,是true,返回的是value
$(function(){ var arr = ['1234','jd','dang','12d3']; var a = $.grep(arr,function(value,index){ return value.indexOf('d') > -1; }); alert(a); // alert(a[1]); // var str = 'dangxingming'; // alert(str.indexOf('k')); });