<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>搜索框输入文字自动提示</title> <link rel="stylesheet" href="./asset/bootstrap/dist/css/bootstrap.min.css"> <style type="text/css"> .container { padding-top: 150px; } .list-group { display: none; } </style> </head> <body> <div class="container"> <div class="form-group"> <input type="text" class="form-control" placeholder="请输入搜索关键字" id="search"> <ul class="list-group" id="list-box"> </ul> </div> </div> <script src="./js/ajax.js"></script> <script src="./js/template-web.js"></script> <script type="text/html" id="tpl"> {{each result }} <li class="list-group-item">{{$value}}</li> {{/each}} </script> <script> var search = document.querySelector("#search") var listBox = document.querySelector('#list-box') var timer = null search.oninput = function() { clearTimeout(timer) var key = this.value; if (key.trim().length == 0) { listBox.style.display = 'none'; return } timer = setTimeout(function() { ajax({ type: 'get', url: 'http://localhost:3001/searchAutoPrompt', data: { key: key }, success: function(result) { var html = template("tpl", { result: result }) listBox.innerHTML = html listBox.style.display = 'block' }, error: function() {} }) }, 800) } </script> </body> </html>