我有一个以下结构的 div 列表 -
HTML
<div class="firstDiv">
<input type="text" id="searcher" placeholder="Search names (start typing)">
<div class="secondDiv">
<div class="entryDiv">
<input id="colin">
</div>
<div class="entryDiv">
<input id="chris">
</div>
<div class="entryDiv">
<input id="zander">
</div>
</div>
</div>
JS
$(document).ready(function () {
$("#searcher").on("keyup click input", function () {
if (this.value.length > 0) {
$(".secondDiv entryDiv").hide().filter(function () {
return $(this).text().toLowerCase().indexOf($("#searcher").val().toLowerCase()) != -1;
}).show();
}
else {
$(".secondDiv entryDiv").hide();
}
});
});
我尝试做的是使用搜索框 - searcher
使用 jquery,以便在按键时 entryDiv
根据 动态显示或隐藏id="colin"
输入的值取决于键入的内容。因此,如果用户输入字母“c”,则包含“colin”和“chris”的两个 div 将保留,但“zander”将被删除。如果搜索框为空,则列表默认返回原始 View 。
很像 here. 所示的示例
最佳答案
首先,您的问题指定
So if a user types in the letter "c" the two divs containing "colin" and "chris" would be left present however "zander" would be removed
您的输入都不包含任何内容,它们都有 ID。也许您想要的是,例如
<input value="colin">
这将使字段包含该文本。
接下来,您的选择器缺少句点:
$(".secondDiv entryDiv")....
应该是
$(".secondDiv .entryDiv")....
最后,这是一个工作示例
$("#searcher").on("keyup click input", function () {
var val = $(this).val();
if (val.length) {
$(".secondDiv .entryDiv").hide().filter(function () {
return $('input',this).val().toLowerCase().indexOf(val.toLowerCase()) != -1;
}).show();
}
else {
$(".secondDiv .entryDiv").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="firstDiv">
<input type="text" id="searcher" placeholder="Search names (start typing)">
<div class="secondDiv">
<div class="entryDiv">
<input value="colin">
</div>
<div class="entryDiv">
<input value="chris">
</div>
<div class="entryDiv">
<input value="zander">
</div>
</div>
</div>
关于javascript - 动态搜索div列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28346196/