搜索框輸入文字自動提示


<!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>


免責聲明!

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



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