我有一个搜索框。我使用 jQuery 和 keyup 来过滤重复的 div。
每个 div 看起来像这样:
<div class="searchCell" id="searchCell' . $id . '">';
<div class="friendName">
// someNameOutputWithPHP.
</div>
</div>
现在,我想根据名称文本进行过滤。如果 someNameOutputWithPHP 包含搜索查询,则整个 searchCell 应 show()。如果没有,整个 searchCell 应该 hide()。
但这不起作用:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
$(".searchCell > .friendName:contains(" + searchValue + ")").show();
});
});
</script>
<小时/>
<小时/>
编辑
新问题:我得到了 div show() 来显示我想要的方式。但是 :contains 不能完全正常工作。
例如:假设其中一个名字是 Ryan。当我搜索“Ryan”时,我什么也没得到。但是当我搜索“yan”时,我得到了 Ryan div。
出了什么问题?
这是:包含代码:
$(".friendName:contains(" + searchValue + ")").parent().show();
最佳答案
这是因为您隐藏了 .searchCell,然后显示其子级 .friendName div,尽管获得了显示属性,但由于父级被隐藏,因此不会显示。
试试这个:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
//$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
// OR
//$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
// OR
$(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
});
});
</script>
关于php - jQuery - 使用 :contains for instant search with nested divs/classes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4848452/