JQuery实现一个页面内搜索定位功能

 因为前端设计页面需要实现一个页面内搜索实现“Search Suggestion”效果的功能。本功能不适用于检索数据集过大的检索,仅仅是页面内数据list的本地检索功能。

实现思路是通过JQuery的循环遍历各个div节点,对关键字匹配成功之后对div展示,否则对div隐藏。

一、需要HTML渲染出所有的搜索节点

HTML代码如下:

<div class="input-group">
    <input id="search-text" type="text" class="form-control input-sm" onkeyup="return searchKeyPress(window.event);" placeholder="点击这里检索">
</div>

<div class="list-group comp-list" id="node-option-show">
    <div class="list-group-item" keywords="freeChargeLabel">
        <i class="fa fa-comment fa-fw"></i> freeChargeLabel<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="arrayquantity">
        <i class="fa fa-comment fa-fw"></i> arrayquantity<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="tbGold">
        <i class="fa fa-comment fa-fw"></i> tbGold<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="payInfo">
        <i class="fa fa-comment fa-fw"></i> payInfo<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="itemInfo">
        <i class="fa fa-comment fa-fw"></i> itemInfo<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="orderInfo">
        <i class="fa fa-comment fa-fw"></i> orderInfo<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="rightPush">
        <i class="fa fa-comment fa-fw"></i> rightPush<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="rebateTip">
        <i class="fa fa-comment fa-fw"></i> rebateTip<span class="pull-right text-muted small"></span>
    </div>
    <div class="list-group-item" keywords="safeTips">
        <i class="fa fa-comment fa-fw"></i> safeTips<span class="pull-right text-muted small"></span>
    </div>
</div>

二、JS代码如下:

function searchKeyPress(e) {
    var keynum = window.event ? e.keyCode : e.which;
    if (13 == keynum
        || (keynum >= 65 && keynum <= 90)
        || (keynum >= 97 && keynum <= 122)
        || 8 == keynum) {
        searchDomain();
    }
}

function searchDomain() {
    var searchText = $("#search-text").val();
    if (searchText != "" && searchText != null) {
        searchText = searchText.toLowerCase();
        $("#node-option-show .list-group-item").each(function () {
            var dataVal = $(this).attr("keywords");
            dataVal = dataVal.toLowerCase();
            if (dataVal.indexOf(searchText) <= -1) {
                $(this).hide();
            }
        });
    } else {
        $("#domain-list-show .domain-info").each(function () {
            $(this).show();
        })
    }
}

相关推荐