2016-04-15 101 views
0

我想讓我的搜索框,通過我的網站上的幾個圖像過濾。所以如果我在搜索框中鍵入omniknight,其餘的圖像應該變暗。我正在嘗試做什麼可以在此網站上查看:http://dotaedge.com/。我試過了這個問題的答案:Filter images based on search input of image title但不起作用。基於圖像名稱的搜索輸入過濾圖像

既然我有這個標記:

<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> 

我嘗試使用下面的代碼通過圖像進行過濾:

$(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(); 
    } 
    }); 
}); 
}); 
+0

它的工作原理...檢查你的控制檯,你有任何錯誤? – Adjit

+0

Uncaught ReferenceError:$未定義(16:54:53:687 | error,javascript) at(匿名函數)(HeroBuilder.php:23:10) –

+0

這意味着您沒有正確添加'jQuery'您的網頁。確保你在''標記中有'' – Adjit

回答

1

您的原始代碼工作正常。您需要確保您的網頁中包含jQuery庫。

一定要在您的<head>標籤中包含此項。這將確保添加jQuery庫,並允許您的函數工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>‌​ 
1

您可以使用JavaScript indexOf功能來搜索一個子串串。 試試這個

if ($(this).attr('hero-name').indexOf(filter) < 0) { 
     $(this).fadeOut(); 

    // Show the div item if the phrase matches 
} 
+0

indexOf實際上是一個Javascript功能! –

+0

你是對的http://stackoverflow.com/users/1086164/xcrkx-typhoon –

1

使用的indexOf檢查filter出現在元素的hero-name屬性

// 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(); 
}