今天做了一个网页上的搜索框
程序员文章站
2022-06-03 22:00:52
...
在搜索框中输入内容时,符合条件的内容会在下拉框中显示,如果没有符合条件的内容会提示没有符合条件的搜索。
<div class="search"> <div class="search-input"> <input onkeyup="Search.init(['name','hello','hi','happy'])" placeholder="搜索商家"> <i class="icon-search"></i> <ul class="dropdown-menu nav sidebar-nav search-result hidden" role="menu"> </ul> </div> </div>
<script> $(document).ready(function () { }); var Search = function () { function show_select_result(result) { if (result.length == 0) { not_search_result(); } else { clear_search_result(); _.each(result, function (item) { $('.search-result').append("<li><a href='#'>" + item + "</a></li>"); }) } } function clear_search_result() { $('.search-result li').remove(); $('.search-result p').remove(); } function not_search_result() { clear_search_result(); $('.search-result').append("<p>没有此类搜索结果</p>"); } return { init: function (array) { var search = $('.search-input input').val(); if(search.length > 0) { $('.search-result').removeClass('hidden'); if(array.length != 0) { var result = []; _.each(array, function(el) { if (el.indexOf(search) != -1) { result.push(el); } }) show_select_result(result); } else{ not_search_result(); } } else{ $('.search-result').addClass('hidden') } } } }(); </script>