Как сделать поиск <input>в поле, где он находит изображения по атрибуту html alt - PullRequest
0 голосов
/ 06 ноября 2019

У меня есть поле поиска ввода, где я сделал это, чтобы отфильтровать изображения по имени и отобразить поле, которое содержит написанное имя или часть имени. Но теперь я хочу добавить поиск по атрибуту 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();
        } 
    });
};

Ответы [ 3 ]

2 голосов
/ 06 ноября 2019

Вы можете просто добавить || $("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>
1 голос
/ 06 ноября 2019

Тег alt действительно должен быть описанием изображения для программ чтения с экрана. Если вы хотите сохранить категорию, рассмотрите возможность использования атрибута data- *.

Может быть, тоже использовать класс в тегах p + img, просто чтобы быть конкретным на случай, если что-нибудь еще будет добавлено туда.

Также не должно быть дубликатов идентификаторов.

Я бы подошел к этому примерно так:

HTML:

<input type="text" id="inputValue" placeholder="Type to search" />
<button onclick="search()" type="button">SEARCH</button>

<div class="imgBox">
    <img class='main-img' src="Photos/20130610_171751.jpg" data-category="track" alt="Silverstone racetrack finish line"> 
    <p class='title'>Title009</p>
</div>

<div class="imgBox">
    <img class='main-img' src="Photos/20130610_171751.jpg" data-category="carting" alt="Two carts battling for first place"> 
    <p class='title'>Title009</p>
</div>

<div class="imgBox">
    <img class='main-img' src="Photos/20130610_171751.jpg" data-category="driver" alt="Steve Jones, racing driver, in 1st place on the podium"> 
    <p class='title'>Title009</p>
</div>

JS:

function search(){
    let keyword = $("#inputValue").val().toLowerCase();
    $(".imgBox").hide();
    $('.imgBox').each(function() {
        if ( $(this).find('.title').text().toLowerCase().indexOf(keyword) >= 0 || $(this).find('.main-img').attr('data-category').toLowerCase().indexOf(keyword) >= 0) {
            $(this).show();
        } 
    });
};
0 голосов
/ 07 ноября 2019

Чем вы все отвечаете. Можете ли вы сказать мне, если сейчас я хочу отфильтровать массив, который содержит objectcts (файл JSON). Как мне сделать это правильно?

arrayPhotos = [{
    "location": "Photos/_DSC0150.jpg",
    "title": "Title001",
    "id": "image_id_001",
    "tags": [ "building", "city", "hotel"]
  },
  {
    "location": "Photos/_DSC0226.jpg",
    "title": "Title002",
    "id": "image_id_002",
    "tags": [ "fruit", "palm"]
  },
  {
    "location": "Photos/_DSC0442.jpg",
    "title": "Title003",
    "id": "image_id_003",
    "tags": [ "building" , "catedral" , "history"]
  },
]
let inputFilter = $("#inputValue").val().toLowerCase();
filteredArrayPhotos = arrayPhotos.filter(function () {

  //Here i need to check if some of the characters in the search field match the
  // ones in `arrayPhotos` .  And if they do , i want those images to added to 
  // `filteredArrayPhotos` 
      })

И у меня есть поле ввода поиска:

<input type="text" id="inputValue" placeholder="Type to search by name"></input>
    <button onclick="filterImagesByName()" type="button">Search</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...