我的脚本有一个小问题,我想根据搜索查找并显示不同的 div。原始脚本是我找到并用于联系人列表的脚本,现在我想对其进行配置以执行其他操作。 Original code (JSFiddle)
我编辑的代码:
$('.Fruit').hide();
$('#search').click(function() {
$('.Fruit').hide();
var txt = $('#search-criteria').val();
$('.Fruit').each(function() {
if ($(this).id.toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="Fruit" id="Apple">
<h3>Some text about apples</h3>
</div>
<div class="Fruit" id="Orange">
<h3>Some text about oranges</h3>
</div>
不知道你是否明白我想要实现的目标......?在本例中,我有两个 div - Apple 和 Orange。默认情况下,两者都是隐藏的,但是如果我在搜索字段中输入 Apple 并按下搜索按钮,div“Apple”将显示,如果我搜索“Orange”,那么显然我希望“Orange”div展示。如果我搜索其他任何内容,只要没有 id 与搜索词匹配的 div,就不会显示任何内容。
所以基本上我正在尝试构建一个预加载内容的数据库,可以快速搜索和显示该内容,而无需重新加载页面。
据我所知,错误是当我尝试处理并比较 div id 与 JS 中第 6 行的搜索词时。有谁知道如何做到这一点并使其发挥作用?或者有人有其他解决方案可以执行此任务吗?
最佳答案
问题是因为 jQuery 对象没有 id
属性。您需要使用 prop('id')
或仅使用 this.id
。
另请注意,您可以通过将匹配的 id 属性设置为小写来改进逻辑,然后将输入转换为小写,然后您可以使用普通选择器,如下所示:
$('#search').click(function() {
var txt = $('#search-criteria').val();
if (txt)
$('.fruit').hide().filter('#' + txt.toLowerCase()).show();
});
.fruit {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>
关于javascript - 根据搜索显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47377956/