JS實現聯想輸入(一)


這里是我們的項目中的一個使用JS實現聯想輸入的功能代碼,在此做個小的記錄並且將它分享給大家希望對園中的朋友有用!

我將分享三段都非常簡單的代碼,僅僅作為個人的一點小小的積累而已!

1:后台的Action方法的代碼,用於取數據,查詢語句是模糊查詢的方式(如果數據庫中的數據相似度非常大,可以采用分頁的方式取部分的數據,比如:取十條記錄)。

    /**
     * @說明:這是一段偽碼,主要想說明從后台返回的數據是JSON格式的,並且形如:[{"linkDataProperty":xxx1},{"linkDataProperty":xxx2},{"linkDataProperty":xxx3}]
     * @author godtrue
     * @修改時間:2014-02-23
     * @param
     * @return
     */
    public void getLinkDataList(){
linkData.setLinkDataProperty(linkDataProperty); List
<LinkData> linkDataList= linkDataService.getLinkDataList(linkData); if(linkDataList!=null&&linkDataList.size()>0){ StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("["); for(int i=0;i<linkDataList.size()-1;i++){ stringBuffer.append("{\"linkDataProperty\":\"").append(linkDataList.get(i).getLinkDataProperty()).append("\"},"); } stringBuffer.append("{\"linkDataProperty\":\"").append(linkDataList.get(linkDataList.size()-1).getLinkDataProperty()).append("\"}]"); renderJson(ServletActionContext.getResponse(),stringBuffer.toString()); }else{ renderJson(ServletActionContext.getResponse(),"[]"); } }
renderJson方法的源碼:
    /** 
     * 直接輸出純JSON 
     */ 
    public void renderJson(HttpServletResponse response, String text) { 
    	PrintWriter out = null;
    	response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		try {
			out = response.getWriter(); 
			out.write(text);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			 if (out != null) { 
				 out.flush(); 
	             out.close(); 
	             out = null; 
	          } 
		}
    }
說明:假設上面的代碼中LinkData是一個對象其中他有一個屬性是linkDataProperty(在此Aciton對象中有linkData和linkDataProperty的聲明和對應的SET/GET方法,所以們的值在前后台能相互的傳送),linkDataService是業務層的一個接口對象,它調用對應的方法獲得對應的模糊查詢的數據結果集linkDataList,然后將結果集中的數據封裝成單列結構的JSON格式的數據形如:[{"linkDataProperty":xxx1},{"linkDataProperty":xxx2},{"linkDataProperty":xxx3}]

2:前台JSP中的HTML代碼,這段代碼主要是展示HTML輸入框和為聯想輸入的下拉選項列表做支撐的
                 <td><input style="width:100%;" id="linkDataProperty" name="linkData.linkDataProperty" type="text" 
onkeyup
="getLinkData();" /> <div id="popup" style="position: absolute;"> <table width="100%" bgcolor="#fffafa"> <tbody id="popupBody"></tbody> </table> </div> </td>:

3:前台JSP中的javaScript代碼,當然這段代碼具有一定的通用性,最好封裝在一個單獨的js文件中更好一些(這也是實現此功能最為關鍵的一段代碼,原理很簡單:利用ajax動態調用后台的方法獲取對應的聯想輸入的數據,然后將數據拼裝成下拉選項列表的形式,再在對應的列表選項上添加對應的事件來控制選中的選項數據)

            function getLinkData() {
                var popupDiv = document.getElementById("popup");//獲得對應的div對象
                var popupBody = document.getElementById("popupBody");//獲得對應的tbody對象
                var linkDataProperty = document.getElementById("linkDataProperty"); //獲得對應的輸入框對象
                clearModels();//清除聯想輸入提示框的內容
                //利用ajax獲取后台的模糊查詢的數據,並且封裝成下拉列表的形式展現出來
                $.ajax({
                    type : "post",//提交的方法為post
                    url : "getLinkDataList.action",//對應的Action提交的路徑
data:{linkDataProperty:linkDataProperty.value},//從前台傳遞到后台的查詢語句的參數 dataType : "json", //從Action中返回的數據的類型為json類型的 error:function(){ alert("沒有對應的數據,請查看輸入的查詢條件!"); }, success : function(data) {//當Ajax提交成功時調用的方法 if(data.length==0){return;} setOffsets();//設置聯想輸入下拉列表提示框的位置 var tr,td,text; for (var i = 0; i < data.length; i++) {//根據返回的值,手動的拼tbody的內容 text = document.createTextNode(data[i].linkDataProperty);//從Action中返回的數據中取出linkDataProperty的值 td = document.createElement("td");//創建一個td的對象 tr = document.createElement("tr");//創建一個tr的對象 td.mouseOver = function(){this.className="mouseOver;"}; td.mouseOut = function(){this.className="mouseOut;"}; td.onclick = function(){populateModel(this)};//單擊td是的方法為populateModel td.appendChild(text); tr.appendChild(td); popupBody.appendChild(tr); } }}); //點擊下拉列表中的某個選項時調用的方法 function populateModel(cell) { clearSelect(); linkDataProperty.value = cell.firstChild.nodeValue; //initOtherData(linkDataProperty.value);利用輸入框中的數據調用其他方法,初始化其他數據 clearModels();//清除自動完成行 } //清除自動完成行,只要tbody有子節點就刪除掉,並且將將外圍的div的邊框屬性設置為不可見的 function clearModels() { while (popupBody.childNodes.length > 0) { popupBody.removeChild(popupBody.firstChild); } popupDiv.style.border = "none"; } //設置下拉列表的位置和樣式 function setOffsets() { var width = linkDataProperty.offsetWidth;//獲取linkDataProperty輸入框的相對寬度 var left = getLeft(linkDataProperty); var top = getTop(linkDataProperty) + linkDataProperty.offsetHeight; popupDiv.style.border = "black 1px solid"; popupDiv.style.left = left + "px"; popupDiv.style.top = top + "px"; popupDiv.style.width = width + "px"; } //獲取指定元素在頁面中的寬度起始位置 function getLeft(e) { var offset = e.offsetLeft; if (e.offsetParent != null) { offset += getLeft(e.offsetParent); } return offset; } //獲取指定元素在頁面中的高度起始位置 function getTop(e) { var offset = e.offsetTop; if (e.offsetParent != null) { offset += getTop(e.offsetParent); } return offset; } } //清空輸入框中的數據 function clearSelect() {
var linkDataProperty=document.getElementById(linkDataProperty);
linkDataProperty.value="";
}

 注:此方法對於單列結構的集合是適用的,可以展示比較好的聯想輸入的效果,並且更可以利用選中的輸入框中的數據再去調用其他的方法來處理其他的數據,特別是再次的調用其他的ajax方法,再從后台獲取數據來做其他的數據處理的時候尤顯的此方法靈活好用!(常常利用輸入框中的數據去后台查詢出一條記錄,所以它多適用於輸入框中的數據能唯一標示出一條記錄的情景下)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM