https://jsfiddle.net/Lh9efLxm/
我在使用实时搜索脚本时遇到了一些问题。
我有一些 div 作为“行”,一些 p 作为“列”声明
作为#filter 的输入字段应该隐藏所有不相关的“行”(div)
$('#results div').hide();
但我似乎有些想念。
有人能帮帮我吗? 谢谢
最佳答案
在您的脚本中,您隐藏和显示所有 #results div
而不是 each
循环中的特定一个。因此,将选择器更改为 this
。
另外,您忘记在 fiddle 中包含 jQuery。
$("#filter").keyup(function() {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(),
count = 0;
// Loop through the comment list
$('#results div').each(function() {
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).hide(); // MY CHANGE
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show(); // MY CHANGE
count++;
}
});
});
.header {
display: flex;
}
.header p {
flex: 1;
font-weight: bold;
}
.results {
display: flex;
}
.results p {
flex: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="filter" type="text">
<div id="header">
<div class="header">
<p>ID</p>
<p>Manufacturer</p>
<p>Type</p>
<p>PS</p>
</div>
</div>
<div id="results">
<div class="results">
<p>1</p>
<p>Toyota</p>
<p>C 200</p>
<p>114</p>
</div>
<div class="results">
<p>2</p>
<p>Mercedes</p>
<p>C 220</p>
<p>144</p>
</div>
</div>
关于javascript - 使用输入过滤器在 Div 上进行实时搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44736054/