jQuery 实现前端模糊匹配与首字母搜索

实现效果

源码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>搜索框测试Demo</title>
    <style>
        .searchDiv {width: 400px;height: 400px;margin: 150px auto;}
        .on {font-size: 12px;font-weight: 700;color: red;}
        /* 隐藏 拼音 标签 */
        p {display: none;}
    </style>
    <script type="text/javascript" src="../asset/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
            //键盘按键弹起时执行
            $('#index').keyup(function(){
                var index = $.trim($('#index').val().toString()); // 去掉两头空格
                if(index == ''){ // 如果搜索框输入为空
                    $('li').removeClass('on');
                    return false;
                }
                var parent = $('ul');
                $('li').removeClass('on');
                //选择包含文本框值的所有加上focus类样式,并把它(们)移到ul的最前面
                // prependTo() 方法在被选元素的开头(仍位于内部)插入指定内容
                // contains 选择器,选取包含指定字符串的元素
                $("li:contains('"+index+"')").prependTo(parent).addClass('on');
                $("p:contains('"+index+"')").parent().prependTo(parent).addClass('on');
            });
        });
    </script>
</head>
<body>
    <div class="searchDiv">
        我要搜:<input type="text" id="index"/>
        <ul>
            <li>郑州的文武<p>zzdww</p></li>
            <li>我来自新乡市<p>wlzxxs</p></li>
            <li>我的母校是中原工学院<p>wdmxszygxy</p></li>
            <li>我叫郑斌<p>wjzb</p></li>
            <li>芳龄22<p>fl22</p></li>
        </ul>
    </div>
</body>
</html>

注意

用到了 jQuery 提供的 :contains 选择器,详情参考:http://www.w3school.com.cn/jquery/selector_contains.asp

后期优化,搜索标题的拼音首字母应由后台程序生成,详情参考:http://blog.csdn.net/chunlongyuan/article/details/8514147

原文地址:https://www.cnblogs.com/zhengbin/p/6790657.html