---
title: "使用DWR实现搜索自动提示(二)"
author: "sprite"
date: "2007-06-28T21:49:37Z"
tags: []
slug: "dwr"
draft: false
lastmod: "2007-06-28T21:49:37Z"
id: 95207
url: "https://sprite.iteye.com/blog/95207"
---

js 代码

001. TextSuggest = Class.create();
002. TextSuggest.prototype = {
003. //构造函数
004. initialize: function(elementId /\*:HTMLInputElementId\*/,oProvider /\*:SuggestionProvider\*/, options/\*:cssStyle and display count  ect\*/) {
005. this.id          = elementId;
006. this.provider    = oProvider;
007. var browser      = navigator.userAgent.toLowerCase();
008. this.isIE        = browser.indexOf("msie") != -1;
009. this.isOpera     = browser.indexOf("opera")!= -1;
010. this.isMozilla   = (browser.indexOf("gecko")!= -1 && browser.indexOf("mozilla")!= -1);
011. this.textInput   = $(this.id);
012. this.suggestions = new Array();
013. this.setOptions(options);
014. this.injectSuggestBehavior();
015. },
016. //设置参数
017. setOptions: function(options) {
018. this.options = {
019. //层样式
020. suggestDivClassName: 'suggestDiv',
021. //选项样式
022. suggestionClassName: 'suggestion',
023. //匹配样式
024. matchClassName     : 'match',
025. //是否匹配输入框宽度
026. matchTextWidth     : true,
027. //选项颜色
028. selectionColor     : '#b1c09c',
029. //是否从头匹配
030. matchAnywhere      : false,
031. //是否忽略大小写
032. ignoreCase         : false,
033. //显示数目
034. count              : 10,
035. //隐藏字段的Id
036. hiddenId           : ''
037. }.extend(options || {});
038. },
039. //注入输入提示行为
040. injectSuggestBehavior: function() {
041. if ( this.isIE ||this.isMozilla){
042. this.textInput.setAttribute('autocomplete','off');
043. }
044. //创建控制器
045. var keyEventHandler = new TextSuggestKeyHandler(this);
046. //主要是为了避免在按回车的时候把表单提交 目前未能实现
047. //new Insertion.After( this.textInput,'' );
048. // new Insertion.After( this.textInput,'' );
049. //创建div层
050. this.createSuggestionsDiv();
051. },
052. //处理输入信息
053. handleTextInput: function() {
054. var previousRequest  = this.lastRequestString;
055. this.lastRequestString =this.textInput.value.replace(/(^\\s\*)|(\\s\*$)/g, "");
056. if ( this.lastRequestString == "" ||this.lastRequestString.length &lt;=0 ){
057. //如果有hidden的变量，要将变量置为空
058. if(this.options.hiddenId != "" && this.options.hiddenId.length &gt;0){
059. $(this.options.hiddenId).value = "";
060. }
061. this.hideSuggestions();
062. }else if ( this.lastRequestString != previousRequest ){
063. //访问数据源
064. this.sendRequestForSuggestions();
065. }
066. },
067. //选择框上移
068. moveSelectionUp: function() {
069. if ( this.selectedIndex &gt; 0 ) {
070. this.updateSelection(this.selectedIndex - 1);
071. }
072. },
073. //选择框下移
074. moveSelectionDown: function() {
075. if ( this.selectedIndex &lt; (this.suggestions.length - 1)  ) {
076. this.updateSelection(this.selectedIndex + 1);
077. }
078. },
079. //更新当前选择信息
080. updateSelection: function(n) {
081. var span = $( this.id + "\_" + this.selectedIndex );
082. if ( span ){
083. //消除以前的样式
084. span.style.backgroundColor = "";
085. }
086. this.selectedIndex = n;
087. var span = $( this.id + "\_" + this.selectedIndex );
088. if ( span ){
089. //更新新样式
090. span.style.backgroundColor = this.options.selectionColor;
091. }
092. },
093. //发送请求
094. sendRequestForSuggestions: function() {
095. if ( this.handlingRequest ) {
096. this.pendingRequest = true;
097. return;
098. }
099. this.handlingRequest = true;
100. this.callDWRAjaxEngine();
101. },
102. //使用DWR访问后台
103. callDWRAjaxEngine: function() {
104. //清空以前的记录
105. if(this.suggestions.length&gt;0){
106. this.suggestions = null;
107. }
108. //保存当前对象指针
109. var tempThis = this;
110. this.provider(this.lastRequestString,function(ajaxResponse){
111. tempThis.suggestions = ajaxResponse;
112. if ( tempThis.suggestions.length == 0 ) {
113. //如果有hidden的变量，要将变量置为空
114. if(tempThis.options.hiddenId != "" && tempThis.options.hiddenId.length &gt;0){
115. $(tempThis.options.hiddenId).value = "";
116. }
117. tempThis.hideSuggestions();
118. }else {
119. tempThis.updateSuggestionsDiv();
120. tempThis.showSuggestions();
121. tempThis.updateSelection(0);
122. }
123. tempThis.handlingRequest = false;
124. if ( tempThis.pendingRequest ) {
125. tempThis.pendingRequest    = false;
126. tempThis.lastRequestString = this.textInput.value;
127. tempThis.sendRequestForSuggestions();
128. }
129. });
130. },
131. //显示信息
132. setInputFromSelection: function() {
133. var suggestion  = this.suggestions\[ this.selectedIndex ];
134. if(typeof(suggestion) != 'undefined'){
135. //如果有hidden的变量，要将变量置赋值
136. if(this.options.hiddenId != "" && this.options.hiddenId.length &gt;0){
137. $(this.options.hiddenId).value = suggestion.id;
138. }
139. this.textInput.value = suggestion.districtName;
140. }
141. this.hideSuggestions();
142. },
143. //
144. getLeft : function () /\*:int\*/ {
145. var oNode = this.textInput;
146. var iLeft = 0;
147. while(oNode.tagName != "BODY") {
148. iLeft += oNode.offsetLeft;
149. oNode = oNode.offsetParent;
150. }
151. return iLeft;
152. },
153. getTop : function () /\*:int\*/ {
154. var oNode = this.textInput;
155. var iTop = 0;
156. while(oNode.tagName != "BODY") {
157. iTop += oNode.offsetTop;
158. oNode = oNode.offsetParent;
159. }
160. return iTop;
161. },
162. //显示层
163. showSuggestions: function() {
164. var divStyle = this.suggestionsDiv.style;
165. if( divStyle.display != ''){
166. this.positionSuggestionsDiv();
167. divStyle.display = '';
168. }
169. if(isIE){
170. //创建与弹出div相同样式的iframe,来修复IE6及以下版本中div不能遮住select控件的bug
171. if(!this.iframeSuggestions){
172. this.iframeSuggestions = document.createElement("iframe");
173. var iframeStyle = this.iframeSuggestions.style;
174. iframeStyle.position ='absolute';
175. iframeStyle.zIndex = 100;
176. iframeStyle.top = divStyle.top;
177. iframeStyle.left = divStyle.left;
178. iframeStyle.width = divStyle.width;
179. iframeStyle.height = this.suggestionsDiv.offsetHeight;
180. iframeStyle.display = '';
181. this.textInput.parentNode.appendChild(this.iframeSuggestions);
182. }
183. var iframeStyle = this.iframeSuggestions.style;
184. iframeStyle.position ='absolute';
185. iframeStyle.zIndex = 100;
186. iframeStyle.top = divStyle.top;
187. iframeStyle.left = divStyle.left;
188. iframeStyle.width = divStyle.width;
189. iframeStyle.height = this.suggestionsDiv.offsetHeight;
190. iframeStyle.display = '';
191. }
192. },
193. //定位层
194. positionSuggestionsDiv: function() {
195. var top = (this.getTop()+this.textInput.offsetHeight) ;
196. var left = this.getLeft() ;
197. var width = this.textInput.offsetWidth ;
198. var divStyle  = this.suggestionsDiv.style;
199. divStyle.top  = top  + "px";
200. divStyle.left = left + "px";
201. if ( this.options.matchTextWidth ){
202. divStyle.width = width+ "px";
203. }
204. },
205. //隐藏层
206. hideSuggestions: function() {
207. this.suggestionsDiv.style.display = 'none';
208. if(isIE){
209. if(this.iframeSuggestions)
210. this.iframeSuggestions.style.display = 'none';
211. }
212. },
213. //创建层
214. createSuggestionsDiv: function() {
215. this.suggestionsDiv = document.createElement("div");
216. this.suggestionsDiv.className = this.options.suggestDivClassName;
217. var divStyle = this.suggestionsDiv.style;
218. divStyle.position = 'absolute';
219. divStyle.zIndex   = 101;
220. divStyle.display  = "none";
221. this.textInput.parentNode.appendChild(this.suggestionsDiv);
222. },
223. //更新层
224. updateSuggestionsDiv: function() {
225. this.suggestionsDiv.innerHTML = "";
226. //如果有hidden变量，清空隐藏字段的值
227. if(this.options.hiddenId != "" && this.options.hiddenId.length &gt;0){
228. $(this.options.hiddenId).value ="";
229. }
230. var suggestLines = this.createSuggestionSpans();
231. for ( var i = 0 ; i &lt; suggestLines.length ; i++ ){
232. this.suggestionsDiv.appendChild(suggestLines\[i]);
233. }
234. },
235. //创建层中的选项span
236. createSuggestionSpans: function() {
237. var regExpFlags = "";
238. if ( this.options.ignoreCase )
239. regExpFlags = 'i';
240. var startRegExp = "^";
241. if ( this.options.matchAnywhere )
242. startRegExp = '';
243. //正则表达式匹配
244. var regExp  = new RegExp( startRegExp + this.lastRequestString, regExpFlags );
245. var suggestionSpans = new Array();
246. for ( var i = 0 ; i &lt; this.suggestions.length && i&lt;this.options.count ; i++ )
247. suggestionSpans.push( this.createSuggestionSpan( i, regExp ) )
248. return suggestionSpans;
249. },
250. //创建单个选项span
251. createSuggestionSpan: function( n, regExp ) {
252. var suggestion = this.suggestions\[n];
253. var suggestionSpan = document.createElement("span");
254. suggestionSpan.className = this.options.suggestionClassName;
255. suggestionSpan.style.width   = '100%';
256. suggestionSpan.style.display = 'block';
257. suggestionSpan.id            = this.id + "\_" + n;
258. suggestionSpan.onmouseover   = this.mouseoverHandler.bindAsEventListener(this);
259. suggestionSpan.onclick       = this.itemClickHandler.bindAsEventListener(this);
260. var textValues = this.splitTextValues( suggestion.districtName+"",
261. this.lastRequestString.length,
262. regExp );
263. var textMatchSpan = document.createElement("span");
264. textMatchSpan.id            = this.id + "\_match\_" + n;
265. textMatchSpan.className     = this.options.matchClassName;
266. textMatchSpan.onmouseover   = this.mouseoverHandler.bindAsEventListener(this);
267. textMatchSpan.onclick       = this.itemClickHandler.bindAsEventListener(this);
268. textMatchSpan.appendChild( document.createTextNode(textValues.mid) );
269. suggestionSpan.appendChild( document.createTextNode( textValues.start ) );
270. suggestionSpan.appendChild( textMatchSpan );
271. suggestionSpan.appendChild( document.createTextNode( textValues.end ) );
272. //把小区地址显示在小区名后面
273. //suggestionSpan.appendChild(document.createTextNode("        "+suggestion.address ) );
274. suggestionSpan.innerHTML+="    "+suggestion.address;
275. return suggestionSpan;
276. },
277. //鼠标经过处理
278. mouseoverHandler: function(e) {
279. var src = e.srcElement ? e.srcElement : e.target;
280. var index = parseInt(src.id.substring(src.id.lastIndexOf('\_')+1));
281. this.updateSelection(index);
282. },
283. //鼠标点击处理
284. itemClickHandler: function(e) {
285. this.mouseoverHandler(e);
286. //鼠标点击把数据set入输入框！
287. this.setInputFromSelection();
288. this.hideSuggestions();
289. },
290. //分拆字符串
291. splitTextValues: function( text, len, regExp ) {
292. var startPos  = text.search(regExp);
293. var matchText = text.substring( startPos, startPos + len );
294. var startText = startPos == 0 ? "" : text.substring(0, startPos);
295. var endText   = text.substring( startPos + len );
296. return { start: startText, mid: matchText, end: endText };
297. },
298. //如果只需要显示列表里的文字而已 可以调用此方法
299. getElementContent: function(element) {
300. return element.firstChild.data;
301. }
302. };