<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>搜索框輸入文字自動提示</title>
<link rel="stylesheet" href="/assets/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 searchInp = document.getElementById('search');
// 獲取提示文字的存放容器
var listBox = document.getElementById('list-box');
// 存儲定時器的變量
var timer = null;
// 當用戶在文本框中輸入的時候觸發
searchInp.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:3000/searchAutoPrompt',
data: {
key: key
},
success: function (result) {
// 使用模板引擎拼接字符串
var html = template('tpl', {result: result});
// 將拼接好的字符串顯示在頁面中
listBox.innerHTML = html;
// 顯示ul容器
listBox.style.display = 'block';
}
})
}, 800)
}
</script>
</body>
</html>