1. 程式人生 > >input搜尋提示功能--基於jquery框架

input搜尋提示功能--基於jquery框架

因需求,網站需要一個搜尋提示功能,本想用html5原生控制元件實現,
但部分瀏覽器相容性不好,最後還是自己用jquery實現功能。

效果圖

效果圖

Html程式碼

<section class="search">
    <div class="row">
        <input type="text" placeholder="搜尋" id="Search" name="search">
    </div>
</section>

CSS樣式

     .search{
            width
: 200px
; position: fixed; z-index: 2; margin: auto; bottom: 0; right: 0; left: 0; top: 200px; }
.search input{ width: 200px; border: none; border: solid 1px #00a0e9; height
: 20px
; padding-left: 15px; }
.search input,.search button:focus{ outline: none; } .search button{ width: 20px; background: #00a0e9; border: none; height: 20px; } table{ position
: absolute
; left: 0; width: 215px; border: solid 1px #e0e0e0; }
table td{ height: 0.6rem; padding-left: 15px; }

核心Javascript

//執行程式碼
window.onload = ListenerSearch();

//實時監控搜尋框文字輸入事件
function ListenerSearch(){
    var name = ['1','2','33','41','15','董祕課堂','董祕資料'];
    //實時監控文字輸入
    $("input[name='search']").bind('input propertychange',function () {
        QueryKeyword($(this).val(),name);
    });
}

//檢索數組裡是否有對應關鍵詞
function QueryKeyword(SearchName,ArrayList) {
    //初始化陣列
    var Keyword = [];
    //遍歷陣列內容
    for(var i = 0; i < ArrayList.length; i++){
        //查詢判斷陣列內是否包含關鍵詞
        if(SearchName.length != 0){
            //搜尋框輸入資料全等於陣列內字串引數
            if(SearchName === ArrayList[i].substr(0,SearchName.length)){
                //新增資料
                Keyword.push(ArrayList[i]);
            }
        }
    }
    if(Keyword.length != 0){
        //建立table表單
        CreateTable(Keyword);
    } else {
        //刪除table表單
        RemoveTable();
    }
}

//監控table表單點選事件,修改input內容
function TableOnclick(id) {
    $("#Search").val($("#"+id).html());
    $("#Table").remove();
}

//建立table表單
function CreateTable(Keyword) {
    var TableContent = "";
    for(var i = 0; i < Keyword.length; i++){
        TableContent += "" +
            "<tr>" +
            "<td id='"+i+"' onclick='TableOnclick(this.id)'>"+Keyword[i]+"</td>" +
            "</tr>";
    }
    //table表單不存在時進行建立
    if(!document.getElementById("#Table")){
        var Table = document.createElement('table');
        Table.id = "Table";
        $(".search").append(Table);
    }
    $("#Table").html(TableContent);
}

//刪除table表單
function RemoveTable() {
    $("#Table").remove();
}

注意:以上程式碼只是通過靜態陣列進行互動,若想動態互動,將ListenerSearch()函式下的name引數改成通過ajax取得的陣列引數即可。

瀏覽器相容

  1. 目前,還沒測試相容瀏覽器,若有問題,還請在留言處提出。