基于alt标记的图像jquery搜索过滤器

dsf9zpds  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(320)

我正在构建一个基于alt标记的图像库搜索页面。画廊最终将有超过3000张图片。仅显示与搜索栏中的文本匹配的图像。该页面将在您键入时更新,以反映当前匹配项。到目前为止,我已经有了一个很好的工作模式,这要感谢我在这里找到的关于几乎相同任务的帖子。我需要我的搜索过滤器对大小写和空格不敏感。我当前的代码几乎按照预期工作,但有一个小问题。来自搜索栏的输入不会显示alt标记中数字字符的任何匹配项。

$('img').hide();

$("#myinput").keyup(function() {
  var val = $.trim(this.value);
  val = val.split(" ").join("\\ ");
  if (val === "")
    $('img').hide();
  else {
    $('img').hide();
    $("img[alt*=" + val + " i]").show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myinput" name="search" placeholder="search..." style="width:200px; height: 40px; border-radius: 4px; font-size: 18px;"><br>
<div id="images">
  <a href="https://example.com"><img src="https://picsum.photos/id/100/200/300" alt="Beach 194888" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1002/200/300" alt="Earth 2069" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1003/200/300" alt="Bambi" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1015/200/300" alt="River" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1027/200/300" alt="Roksolana Zasiadko" width=130></a>

</div>
brgchamk

brgchamk1#

这将对带或不带数字的不区分大小写输入进行过滤

const $img = $("#images img");
$("#myinput").on("input",function() {
  $img.hide();
  const val = this.value.trim().toLowerCase();  
  if (val === "") return; 
  $img.filter(function() { return this.alt.toLowerCase().includes(val)  }).show()
});

# images img { display: none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myinput" name="search" placeholder="search..." style="width:200px; height: 40px; border-radius: 4px; font-size: 18px;"><br>
<div id="images">
  <a href="https://example.com"><img src="https://picsum.photos/id/100/200/300" alt="Beach 194888" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1002/200/300" alt="Earth 2069" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1003/200/300" alt="Bambi" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1015/200/300" alt="River" width=130></a>
  <a href="https://example.com"><img src="https://picsum.photos/id/1027/200/300" alt="Roksolana Zasiadko" width=130></a>

</div>

相关问题