jQuery實現模糊搜索效果

使用jQuery中:contains選擇器實現模糊搜索、匹配關鍵字效果。

<div class="warp">
    
    <div class="search_box">
        <input type="text" placeholder="請輸入搜索內容">
        <i class="search_icon"></i>
    </div>

    
    <div class="search_content search_default">
        <ul>
            <li>南京理工</li>
            <li>華師大</li>
            <li>合工大</li>
            <li>哈工大</li>
            <li>復旦</li>
            <li>清華</li>
            <li>同濟</li>
            <li>南開</li>
            <li>中山</li>
            <li>南航</li>
            <li>武漢</li>
        </ul>
    </div>
</div>
body {
	background-color:#f5f5f5;
}
.warp {
	width:50%;
	margin:0 auto;
}
/*清除input默認樣式*/
input {
	border:0;
	background-color:transparent;
}
/*搜索欄*/
.search_box {
	width:60%;
	height:32px;
	box-sizing:border-box;
	box-shadow:1px 1px 4px #e2e2e2;
	padding:0 10px;
	border:1px solid #e2e2e2;
	border-radius:4px;
	background-color:#f5f5f5;
	margin:50px auto 20px auto;
}
.search_box input {
	width:80%;
	height:30px;
	line-height:30px;
	font-size:15px;
	color:#8c8282;
}
.search_box .search_icon {
	float:right;
	display:inline-block;
	width:24px;
	height:24px;
	background:url("img/search.png") no-repeat center center;
	background-size:cover;
	margin-top:3px;
}
/*搜索內容*/
.search_content {
	width:60%;
	margin:0 auto;
	background-color:#fff;
	border-radius:8px;
}
.search_content ul {
	padding-left:0;
}
.search_content li {
	width:90%;
	margin:0 auto;
	height:40px;
	line-height:40px;
	box-sizing:border-box;
	border-bottom:.4px solid #e2e2e2;
	list-style:none;
}
.search_content li:last-child {
	border-bottom:0;
}
.search_content li a {
	color:#8c8282;
}
$(function() {
    var search_input = $(".search_box input"),
        search_content = $(".search_content");
    $(search_input).on("keyup", function() {
        if (search_input.val() == '') {
            $(search_content).show();
        }
        $(".search_content li:contains(" + search_input.val().trim() + ")").show();
        $(".search_content li:not(:contains(" + search_input.val().trim() + "))").hide();


        //第二中方法
        //$(".search_content li").hide().filter(":contains("+ search_input.val().trim() +")").show();
    });
});

搜索功能思路: 當觸發 keyup 鍵盤松開事件時,判斷 input 輸入框中的內容是不是 li 標籤裏包含的內容,包含則該  li 標籤顯示,不包含 則該 li 標籤隱藏。

開發步驟:

1.使用 keyup 鍵盤松開事件,當鍵盤松開時觸發以下內容。

2. 先獲取 input 輸入框中的內容。

3. 利用 jQuery 中 :contains 選擇器判斷 li 標籤中的內容是否包含 input 輸入框中的內容。

4.如果包含則該 li 標籤顯示,否則 則隱藏。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章