首页 > 解决方案 > 怎么做搜索字段,它通过 html alt 属性找到图像

问题描述

我有一个输入搜索字段,我已在其中按名称过滤图像并显示包含所写名称或部分名称的图像。但现在我也想将搜索添加为按属性alt。所以要按名称和标签显示过滤后的图像。

  <input type="text" id="inputValue" placeholder="Type to search"></input>
  <button onclick="Images()" type="button">SEARCH</button>
  <div class="imgBox"><img id="image_id_009" 
       src="Photos/20130610_171751.jpg" alt="track"> 
    <p>Title009</p>
  </div>
  <div class="imgBox"><img id="image_id_009" 
       src="Photos/20130610_171751.jpg" alt="carting"> 
    <p>Title009</p>
  </div>
  <div class="imgBox"><img id="image_id_009" 
       src="Photos/20130610_171751.jpg" alt="driver"> 
    <p>Title009</p>
  </div>

javascript:

function Images(){
    let filtering=$("#inputValue").val().toLowerCase();
    $(".Box").hide();
    $('.Box').each(function(){
        if ($(this).text().toLowerCase().indexOf(filtering) !== -1) {
            $(this).show();
        } 
    });
};

标签: javascriptjquery

解决方案


您可以添加|| $("img", this).attr("alt").toLowerCase().indexOf(filtering) !== -1到现有的if statement

function Images() {
  let filtering = $("#inputValue").val().toLowerCase();
  $(".imgBox").hide();
  $('.imgBox').each(function() {
    if ($(this).text().toLowerCase().indexOf(filtering) !== -1 || $("img", this).attr("alt").toLowerCase().indexOf(filtering) !== -1) {
      $(this).show();
    }
  });
};

注意我已更改$('.Box')$('.imgBox')使示例正常工作

演示

function Images() {
  let filtering = $("#inputValue").val().toLowerCase();
  $(".imgBox").hide();
  $('.imgBox').each(function() {
    if ($(this).text().toLowerCase().indexOf(filtering) !== -1 || $("img", this).attr("alt").toLowerCase().indexOf(filtering) !== -1) {
      $(this).show();
    }
  });
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inputValue" placeholder="Type to search"></input>
<button onclick="Images()" type="button">SEARCH</button>
<div class="imgBox"><img id="image_id_009" src="Photos/20130610_171751.jpg" alt="track">
  <p>Title009</p>
</div>
<div class="imgBox"><img id="image_id_009" src="Photos/20130610_171751.jpg" alt="carting">
  <p>Title009</p>
</div>
<div class="imgBox"><img id="image_id_009" src="Photos/20130610_171751.jpg" alt="driver">
  <p>Title009</p>
</div>


推荐阅读