基于 ALT 标签的图像的 Jquery 搜索过滤器

蒂姆

我正在为基于 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>

普隆詹

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

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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章