javascript - 如何制作只能在一组 div 中搜索特定元素的搜索过滤器?
问题描述
目前,我可以通过输入大厅容器中的任何内容(包括名称、位置、容量)来搜索大厅,但是,我只想能够过滤搜索大厅名称的结果。
<div id="searchFilter" class="flexColumn">
<label for="searchFilterText">Search for Community Halls</label>
<input type="text" id="searchFilterText" placeholder="Search for the name of a community hall">
</div>
`<div class="hall">
<div class="info">
<p>${data.Halls[halls[i]].Location[0].Address}, ${data.Halls[halls[i]].Location[1].Suburb}<br>Capacity: ${data.Halls[halls[i]].Room[0]["Standing Capacity"]}</p>
</div>
<div class="image">
<img class="img" src="${data.Halls[halls[i]].Description[4].Photos}" alt="${data.Halls[halls[i]]["Hall Name"]}">
</div>
<div class="hallNameBox">
<p class="hallName">${data.Halls[halls[i]]["Hall Name"]}</p>
</div>
</div>`;
$(document).ready(function(){
$("#searchFilterText").on("keyup", function() {
let value = $(this).val().toLowerCase();
$(".hall").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
解决方案
而不是使用toggle
useshow
和hide
.
(使用one
、two
或three
来测试这个简化的示例)。
$(function() {
$("#searchFilterText").on('keyup', function() {
// Grab the value
const value = $(this).val().toLowerCase();
// If it's not empty
if (value) {
// `filter` all the hall elements if
// the text of the hallName element doesn't start with
// the value and hide them
$('.hall').filter(function() {
const text = $(this).find('.hallName').text().toLowerCase();
return !text.startsWith(value);
}).hide();
// Otherwise show them
} else {
$('.hall').show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchFilter" class="flexColumn">
<input type="text" id="searchFilterText" />
</div>
<div class="hall">
<div class="hallNameBox">
<p class="hallName">One</p>
</div>
</div>
<div class="hall">
<div class="hallNameBox">
<p class="hallName">Two</p>
</div>
</div>
<div class="hall">
<div class="hallNameBox">
<p class="hallName">Three</p>
</div>
</div>
推荐阅读
- c# - 让 SignalR 在不总是运行的代码中永远监听
- javascript - Lodash 合并两个数组并对其进行分类
- mongodb - MongoDB:如何添加包含最近子文档的减少值的数组
- java - 我可以在后台的广播接收器中显示自定义视图吗?
- python-3.x - astropy.extern.configobj.configobj.ConfigObjError: Parsing failed with several errors
- javascript - 如何调试 HTML 中脚本标记中编写的 JavaScript
- java - 每周使用 log4j2 创建 zip 文件
- python - 什么是梯度下降。梯度下降能比sklearn线性回归算法给出更好的结果吗
- list - `seqn` 和 `sequenceA` 之间的关系和区别是什么?
- python - Python onedrivesdk - invalid_request 错误