jquery - 如何隐藏列表项过滤html搜索框
问题描述
如何从过滤器 html 搜索框中隐藏列表项。
例如,它仅在我单击搜索框时才显示项目,然后显示项目列表
否则以正常方式隐藏列表项。
- 阿黛尔
- 艾格尼丝
- 比利
- 鲍勃
- 卡尔文
- 克里斯蒂娜
- 辛迪
- 康提
- 拉库姆
- 酷
- 月亮
- 中午
如果有人可以纠正这个请。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 12px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myUL {
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}
</style>
</head>
<body>
<h2>My Phonebook</h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<ul id="myUL">
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul>
<script>
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
</body>
</html>
如果有人可以纠正这个请。
解决方案
您可以做的只是在 DOM 准备好后隐藏 UL el,然后在输入字段设置为焦点时显示列表。使用 jquery 在下面尝试此代码。
$(function(){
$('#myUL').hide();
$('#myInput').on('focus',function(){
$('#myUL').show();
});
})
推荐阅读
- python - 如何将 Keras 转换为 Tensorflow Lite 并从另一种语言中使用?
- docker - Docker compose 权限被卷拒绝
- xamarin - 如何获取已关闭或未关闭电源的配对蓝牙设备列表是 UWP 中的范围
- angular - 此条件将始终返回 'false',因为类型 'SingleDataSet' 和 'number' 没有重叠 ng2chart [angular]
- curl - cURL 它是如何工作的 case 句子 Exclamation mark over 2ea
- javascript - 我们可以在更新 openlayers 6.5 中的填充时为视图设置动画吗?
- linux - AWS 工作区 Golden Image Linux - 将预置用户添加到 docker 组
- javascript - 检查字符串是 HTML 代码还是随机字符
- c - c中的size_t指针与uint32_t指针
- ios - 如何将java枚举案例转换为swift?