繁体   English   中英

根据搜索显示div

[英]Show div depending on a search

我的脚本有一个小问题,我想根据搜索查找并显示不同的div。 我找到了原始脚本并将其用于联系人列表,现在我想对其进行配置以执行其他操作。 原始代码(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例如并按下搜索按钮,则显示“ Apple”的div,如果我改为搜索“ Orange”,则显然我希望“ Orange”的div节目。 如果我搜索其他内容,只要不存在ID与搜索字词匹配的div,就不会显示任何内容。

因此,基本上,我正在尝试构建一个预加载内容的数据库,该数据库可以在不重新加载页面的情况下即时搜索和显示。

据我所知,该错误是当我尝试寻址divs 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM