首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于图像名称搜索输入的图像过滤

基于图像名称搜索输入的图像过滤
EN

Stack Overflow用户
提问于 2016-04-15 15:36:02
回答 3查看 1.2K关注 0票数 0

我试图使我的搜索框,过滤几个图片在我的网站上。所以,如果我在搜索框中键入杂食,其余的图像就会变暗。我想要做的事情可以在这个网站上浏览:http://dotaedge.com/。我试过这个问题的答案:Filter images based on search input of image title,但不起作用。

考虑到我有这个标记:

代码语言:javascript
复制
<input type="text" placeholder="Enter hero name here" id="search">

<a id="Hero-7" class="hero" hero-id="7" href="#" hero-uri="rattletrap" hero-name="Clockwerk">
        <img class="hero-img-small" src="Dota-Heroes-Small/rattletrap_sb.png">
        <div class="hero-action">
            <img class="hero-img-large" src="Dota-Heroes-Hover/rattletrap_hphover.png">
        </div>
    </a>

<a id="Hero-8" class="hero" hero-id="8" href="#" hero-uri="omniknight" hero-name="Omniknight">
        <img class="hero-img-small" src="Dota-Heroes-Small/omniknight_sb.png">
        <div class="hero-action">
            <img class="hero-img-large" src="Dota-Heroes-Hover/omniknight_hphover.png">
        </div>
    </a>

<a id="Hero-9" class="hero" hero-id="9" href="#" hero-uri="huskar" hero-name="Huskar">
        <img class="hero-img-small" src="Dota-Heroes-Small/huskar_sb.png">
        <div class="hero-action">
            <img class="hero-img-large" src="Dota-Heroes-Hover/huskar_hphover.png">
        </div>
    </a>

我试图使用以下代码对图像进行过滤:

代码语言:javascript
复制
$(document).ready(function () {

$(".hero-name").hide();

$("#search").keyup(function(){

    // Retrieve the input field text 
    var filter = $(this).val();

    // Loop through the captions div 
   $(".hero").each(function(){

     // If the div item does not contain the text phrase fade it out
     if ($(this).attr('hero-name').search(new RegExp(filter, "i")) < 0) {
            $(this).fadeOut();

     // Show the div item if the phrase matches 
     } else {
     $(this).show();
     }
    });
 });
});
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-04-15 16:19:14

你的原始代码很好用。您需要确保在您的网页中包含了jQuery库。

一定要将其包含在<head>标记中。这将确保添加了jQuery库,并允许您的函数工作。

代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>‌​
票数 1
EN

Stack Overflow用户

发布于 2016-04-15 15:44:46

您可以使用javascript indexOf函数在字符串中搜索子字符串。尝尝这个

代码语言:javascript
复制
if ($(this).attr('hero-name').indexOf(filter) < 0) {
        $(this).fadeOut();

     // Show the div item if the phrase matches 
 } 
票数 1
EN

Stack Overflow用户

发布于 2016-04-15 15:49:15

使用indexOf检查filter是否存在于元素的hero-name属性中

代码语言:javascript
复制
// Loop through the captions div 
$(".hero").each(function(){

// If the div item does not contain the text phrase fade it out
if (!$(this).attr('hero-name').indexOf(filter) > -1) {
    $(this).fadeOut();

// Show the div item if the phrase matches 
} else {
    $(this).show();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36651357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档