本文分享一個用 JavaScript 實現的文本框輸入智能提示(自動完成)效果,供感興趣的朋友參考。運行效果截圖如下:

整體思路:
1. 監聽文本框事件,這裡採用 keyup 事件,其實 onchange 也可以,不過個人感覺 keyup 的實時反饋更順暢。
2. 根據用戶輸入,通過 ajax 異步請求後台數據。
3. 遍歷返回的結果,逐條渲染到提示區域。
4. 為每條提示加上交互效果:點擊某條即把內容填入文本框,並讓提示列表消失。
5. 後台數據建議拼接成 JSON 格式返回。
具體代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head runat="server"> <title>自動提示</title> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script type="text/ecmascript"> function txtchange() { var nnmae = $("#intxt").val(); $.ajax({ type: "post", url: "ashx/AutoNote.ashx", data: { name: nnmae }, dataType: "json", success: function (data) { $("#tbcontent").html(""); //刪除原有數據 if (data != "null") { for (var i = 0; i < $(data).length; i++) { $("#tbcontent").append('<div class="item" onclick="mousedown(this)">' + data[i].name + '</div>'); } $("#tbcontent").slideDown(); } } }); } //選擇其中的提示內容 function mousedown(object) { $("#intxt").val($(object).text()); $("#tbcontent").fadeOut(); } //文檔框失去焦點,隱藏提示內容 function lost() { $("#tbcontent").fadeOut(); } </script> <style type="text/css"> .item:hover { background-color: Gray; cursor:pointer; } .show { width: 200px; z-index: 10; display: block; } .hidden { width: 200px; z-index: 10; display: none; border:1px solid rgb(80,160,91); border-top:none; } table tr td { margin:none; padding:none; border:none; } </style> </head> <body> <form id="form1" runat="server"> <div style="width: 210px; margin-left:auto; margin-right:auto"> <table> <tr> <td> <input type="text" style="width: 200px;" id="intxt" onkeyup="txtchange()" onblur="lost()"/> </td> </tr> <tr> <td> <div id="tbcontent" class="hidden"> </div> </td> </tr> </table> </div> </form> </body> </html>
這種輸入即提示的交互,在搜索、選擇等場景中相當實用,希望對你學習 JavaScript 有所幫助。