我的网站上有多个div,需要能够通过搜索内容来过滤它们。
搜索应查找div中的标题并隐藏div,其标题不包含搜索框中的短语。此外,搜索应该通过按键盘上的ESC键或按搜索框右侧的小x按钮进行转义。只有在搜索正在使用时才会显示x按钮
<input type="search" placeholder="Search ..." />
我的搜索框看起来像这样,应该过滤下面的div。
<div> <h3>Red</h3> <p>Lorem ipsum dolor est</p> </div>
<div> <h3>Green</h3> <p>Lorem ipsum dolor est</p> </div>
<div> <h3>Blue</h3> <p>Lorem ipsum dolor est</p> </div>
<div> <h3>Orange</h3> <p>Lorem ipsum dolor est</p> </div>
<div> <h3>Yellow</h3> <p>Lorem ipsum dolor est</p> </div>
解决问题最常用的方法是什么,最好是在jQuery或php中?
答案 0 :(得分:1)
编辑:应用此功能也可以处理输入更改。
好吧检查一下......基本的搜索过滤。只需在html中添加适当的类,然后运行此jquery代码即可。这是我刚创造的小提琴。
var $searchContainer = $("#search");
var $contentBoxes = $searchContainer.find(".content");
var $searchInput = $searchContainer.find("#search-input");
var $searchBtn = $searchContainer.find("#search-btn");
$searchBtn.on("click", searchContent);
$searchInput.on("input", searchContent);
function searchContent() {
var userInput;
//Check if call comes from button or input change
if ($(this).is(":button")) {
userInput = $(this).siblings("input").val();
} else {
userInput = $(this).val();
}
//make the input all lower case to make it compatible for searching
userInput = userInput.toLowerCase();
//Loop through all the content to find matches to the user input
$contentBoxes.each(function() {
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if (!searchableContent.includes(userInput)) {
$(this).hide();
} else {
$(this).show();
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search">
<form>
<input type="search" id="search-input" placeholder="Search ..." />
<button id="search-btn" type="button">Search</button>
</form>
<div class="content">
<h3 class="title">Red</h3>
<p class="description">Lorem ipsum dolor est</p>
</div>
<div class="content">
<h3 class="title">Green</h3>
<p class="description">Lorem ipsum dolor est</p>
</div>
<div class="content">
<h3 class="title">Blue</h3>
<p class="description">Lorem ipsum dolor est</p>
</div>
<div class="content">
<h3 class="title">Orange</h3>
<p class="description">Lorem ipsum dolor est</p>
</div>
<div class="content">
<h3 class="title">Yellow</h3>
<p class="description">Lorem ipsum dolor est</p>
</div>
</div>
如果它更好的话,这里有一个小提琴:) https://jsfiddle.net/9p89034t/22/