我试图使我的搜索框,过滤几个图片在我的网站上。所以,如果我在搜索框中键入杂食,其余的图像就会变暗。我想要做的事情可以在这个网站上浏览: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();
}
});
});
});发布于 2016-04-15 16:19:14
你的原始代码很好用。您需要确保在您的网页中包含了jQuery库。
一定要将其包含在<head>标记中。这将确保添加了jQuery库,并允许您的函数工作。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>发布于 2016-04-15 15:44:46
您可以使用javascript indexOf函数在字符串中搜索子字符串。尝尝这个
if ($(this).attr('hero-name').indexOf(filter) < 0) {
$(this).fadeOut();
// Show the div item if the phrase matches
} 发布于 2016-04-15 15:49:15
使用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();
}https://stackoverflow.com/questions/36651357
复制相似问题