程序员一代码搬运工
【Java学习心得和Java学习技术个人总结】

多个自定义搜搜补全框 -实战

多个自定义搜搜补全框 例子

添加多个文本框例子

后台返回数组代码

页面代码基本没啥变化。。

因为与其他 js 冲突了 。。 修改了部分

<script language="javascript">

	var chuliNum = function (id) {
	return "string" == typeof id ? document.getElementById(id) : id;
	}
	var Bind = function(object, fun) {
	    return function() {
	     return fun.apply(object, arguments);
		}
	}
	function AutoComplete(obj,autoObj,arr){
	this.obj=chuliNum(obj); //输入框
	this.autoObj=chuliNum(autoObj);//DIV的根节点
	this.value_arr=arr; //不要包含重复值
	this.index=-1; //当前选中的DIV的索引
	this.search_value=""; //保存当前搜索的字符
	}
	
	AutoComplete.prototype={
		//初始化DIV的位置
		init : function() {
			this.autoObj.style.left = this.obj.offsetLeft + "px";
			this.autoObj.style.top = this.obj.offsetTop + this.obj.offsetHeight+ "px";
			this.autoObj.style.width = this.obj.offsetWidth - 2 + "px";//减去边框的长度2px
		},
		//删除自动完成需要的所有DIV
		deleteDIV : function() {
			while (this.autoObj.hasChildNodes()) {
				this.autoObj.removeChild(this.autoObj.firstChild);
			}
			this.autoObj.className = "auto_hidden";
		},
		//设置值
		setValue : function(_this) {
			return function() {
				_this.obj.value = this.seq;
				_this.autoObj.className = "auto_hidden";
			}
		},
		//模拟鼠标移动至DIV时,DIV高亮
		autoOnmouseover : function(_this, _div_index) {
			return function() {
				_this.index = _div_index;
				var length = _this.autoObj.children.length;
				for (var j = 0; j < length; j++) {
					if (j != _this.index) {
						_this.autoObj.childNodes[j].className = 'auto_onmouseout';
					} else {
						_this.autoObj.childNodes[j].className = 'auto_onmouseover';
					}
				}
			}
		},
		//更改classname
		changeClassname : function(length) {
			for (var i = 0; i < length; i++) {
				if (i != this.index) {
					this.autoObj.childNodes[i].className = 'auto_onmouseout';
				} else {
					this.autoObj.childNodes[i].className = 'auto_onmouseover';
					this.obj.value = this.autoObj.childNodes[i].seq;
				}
			}
		},
		//响应键盘
		pressKey : function(event) {
			var length = this.autoObj.children.length;
			//光标键"↓"
			if (event.keyCode == 40) {
				++this.index;
				if (this.index > length) {
					this.index = 0;
				} else if (this.index == length) {
					this.obj.value = this.search_value;
				}
				this.changeClassname(length);
			}
			//光标键"↑"
			else if (event.keyCode == 38) {
				this.index--;
				if (this.index < -1) {
					this.index = length - 1;
				} else if (this.index == -1) {
					this.obj.value = this.search_value;
				}
				this.changeClassname(length);
			}
			//回车键
			else if (event.keyCode == 13) {
				this.autoObj.className = "auto_hidden";
				this.index = -1;
			} else {
				this.index = -1;
			}
		},
		//程序入口
		start : function(event) {
			if (event.keyCode != 13 && event.keyCode != 38
					&& event.keyCode != 40) {
				this.init();
				this.deleteDIV();
				this.search_value = this.obj.value;
				var valueArr = this.value_arr;
				valueArr.sort();
				if (this.obj.value.replace(/(^\s*)|(\s*$)/g, '') == "") {
					return;
				}//值为空,退出
				try {
					var reg = new RegExp("(" + this.obj.value + ")", "i");
				} catch (e) {
					return;
				}
				var div_index = 0;//记录创建的DIV的索引
				for (var i = 0; i < valueArr.length; i++) {
					if (reg.test(valueArr[i])) {
						var div = document.createElement("div");
						div.className = "auto_onmouseout";
						div.seq = valueArr[i];
						div.onclick = this.setValue(this);
						div.onmouseover = this.autoOnmouseover(this, div_index);
						div.innerHTML = valueArr[i].replace(reg,
								"<strong>$1</strong>");//搜索到的字符粗体显示
						this.autoObj.appendChild(div);
						this.autoObj.className = "auto_show";
						div_index++;
					}
				}
			}
			this.pressKey(event);
			window.onresize = Bind(this, function() {
				this.init();
			});
		}
	}
</script>

页面调用部分

<p><span>活动举办场地</span>
                      <span>
                       <input type="text"   onkeyup="findResult(this,'auto',event)" id="activityAddress"  name="activityAddress" placeholder="请输入中文地址">
                   <!--     <input type="text"   onkeyup="autoComplete1.start(event)" id="activityAddress1"  name="activityAddress" placeholder="请输入中文地址">
      			 -->	  </span>
      				  <a id="addButton" class="addAclass" onclick="getAddressFill();">添加场地</a>
						
                     <span class="hint2 "  id="activityAddressError" ><img src="<c:url value='/resources/risk/images/public/pss_wrong.png' />"/>地址不能为空</span>
                  
                    </p>
                     <div class="auto_hidden" id="auto"><!--自动完成 DIV--></div>
                    <div id="addressmore"  >
                     
                      </div>

调用js

 var  addressNum=0;
//  var autoComplete2,autoComplete1;
  function getAddressFill(){
    addressNum++;
    var strName="activityAddress"+addressNum;
    var autoName="auto"+addressNum;
	var  str="<div  class='rep'><div class='clear'></div><p><span>&nbsp;</span><span> <input type='text' onkeyup=\"findResult(this,'"+autoName+"',event)\" id='"+strName+"' name='activityAddress' placeholder='请输入更多的举办地址'/><div class='auto_hidden' id='"+autoName+"'></div></span><a class='addAclass' onclick=\"sys_remove_element($(this),'rep','');\">删除场地</a>  </p></div>";
	 $("#addressmore").append(str); 
//     if(addressNum=="1" || addressNum==1){
//     	autoComplete1 = new AutoComplete('activityAddress1','auto1',['b111','b12','b22','b3','b4','b5','b6','b7','b8','b2','abd','ab','acd','accd','b1','cd','ccd','cbcv','cxf']);
//     }
//     if(addressNum=="2"){
//         autoComplete2=new AutoComplete('activityAddress2','auto2',['b111','b12','b22','b3','b4','b5','b6','b7','b8','b2','abd','ab','acd','accd','b1','cd','ccd','cbcv','cxf']);
//     }
 }
  
  function findResult(obj,autoId,event){
	  //alert("jinalai");
	    var  city =$("#city").val();
		var  province =$("#province").val();
		//var  address= $("#activityAddress").val();
	   var address=obj.value;
		var  html="";
		if(city!=""&&city!="请选择市"){
			 $("#activityAddressError").hide();
			 $.ajax({   
			    url:baseUrl+'/findAddress.json',  
			    data:{
			    	'name':address,
			    	'city':city,
			    	'province':province
			    },
			    type:'post', //数据发送方式   
			    async: false,
				dataType : "json",
		        success: function(data){
                   var myArray=new Array();
                   for(var i=0;i<data.searchName.length;i++){
                	   myArray.push(data.searchName[i].address);
                   }
			       $("#addButton").show();
			  	  var autoComplete1 = new AutoComplete(obj,autoId,myArray);
				  autoComplete1.start(event);
			     }  
			});	 
		}
	  
	  

  }

 

<script>

var autoComplete=new AutoComplete('activityAddress','auto',['中国','b12','b22','b3','b4','b5','b6','b7','b8','b2','abd','ab','acd','accd','b1','cd','ccd','cbcv','cxf']);

</script>

后台调用代码

@RequestMapping(value = "/findAddress")
	public JSONObject findAddressView(String name ,String city,String province) {
		List<DedecmsAddress> list=new ArrayList<DedecmsAddress>();
//		List<String> list1=new ArrayList<String>();
//		list1.add("中国好声音");
//		list1.add("中国好声音1");
//		list1.add("中国好声音2");
//		list1.add("中国好声音3");
	   if(city==null||city==""){
			return null;
		}
	  

		city=dataService.findRegionByCode(city).getName();
//		//System.out.println(city);
		province=dataService.findRegionByCode(province).getName();
		if(city.equals("市辖区")||city.equals("县")){
		    //直接查询 省下的 地址
			list=cmsService.findCmsList(province,null);
		}else{
			list=cmsService.findCmsList(province,city);
		}
		
		JSONArray array=new JSONArray();

	    String []arrayNum= new  String[8];//默认只有8个
	    JSONObject json= new JSONObject();
	    for (int i = 0; i < list.size(); i++) {
	    	JSONObject address= new JSONObject();
	    	address.put("address", list.get(i).getAddress());
	    	array.add(address);
		}
	    json.put("searchName", array);
//	    array.add(json);		
//		System.out.println(array.toString());
		return json;

	}

 

赞(0)
未经允许不得转载:程序员一代码搬运工 » 多个自定义搜搜补全框 -实战
分享到: 更多 (0)