Использование `keyup` для фильтрации/поиска в моем файле `.json`, который уже отображается в моем html

avatar
Felipe Ceballos
9 августа 2021 в 06:04
190
2
0

Я работаю над этим уже несколько дней, и мне не очень везет. У меня есть файл json ReptilesTX.json с несколькими животными, и я хотел бы иметь возможность окно поиска enter image description here. Затем отфильтруйте уже загруженных животных, чтобы оставить только те, которые соответствуют условиям поиска. Любое руководство о том, как я должен использовать этот подход? Ниже приведено то, что я пробовал до сих пор, но я получаю некоторые ошибки, которые я не знаю, как читать для устранения неполадок. Заранее спасибо за любые советы/помощь.

enter image description here

Вот мой html

 <div id="container">
        <form role="form">
            <div class="form-group">
                <input type="input" class="form-control input-lg" id="txt-search" placeholder="Type your search character">
            </div>

          <p id="postAnimal">Posting goes here</p>
  

    </div>

Сокращенный пример моего файла json

[
  {
    "id": "americanalligator",
    "friendlyName": "American Alligator",
    "scientificName": "Alligator mississippiensis",
    "url": "https://tpwd.texas.gov/huntwild/wild/species/americanalligator/",
    "picturePath": "/assets/americanalligator",
    "description": "The American alligator is a large...",
    "lifeHistory": "An agile swimmer, the American alligator...",
    "habitat": "Alligators are found in or near water....",
    "distribution": "The American alligator is found ..."
  },
  {
    "id": "bullsnake",
    "friendlyName": "Bullsnake",
    "scientificName": "Pituophis catinefer sayi",
    "url": "https://tpwd.texas.gov/huntwild/wild/species/bullsnake/",
    "picturePath": "/assets/bullsnake",
    "description": "The bullsnake is a heavy-bodied snake...",
    "lifeHistory": "Bullsnakes vary in temperament... ",
    "habitat": "Bullsnakes prefer sandy soils in fields...",
    "distribution": "Bullsnakes occur in the western..."

  }
  ]

Мой javascript

const xhr = new XMLHttpRequest();
const Reptiles = "ReptilesTX.json";

xhr.onload = function() {
if (this.readyState == 4 && this.status == 200) {
    var response = JSON.parse(this.responseText);

    let output = '';
    for(let i = 0; i < response.length; i++){

        output +=  `
    <ul id="list">
        <li id="name">${response[i].friendlyName}</li><br>
        <li><img src='${response[i].picturePath}.jpg'</li><br>
        <li><span>Scientific Name: </span>${response[i].scientificName}</li>
        <li><span>Description: </span>${response[i].description}</li><br>
        <li><span>Life History: </span>${response[i].lifeHistory}</li><br>
        <li><span>Habitat: </span>${response[i].habitat}</li><br>
        <li><span>Distribution: </span>${response[i].distribution}</li>
        <li><span>Source: </span><a href="${response[i].url}">Site</a></li>
    </ul>;
    `
    }
    //console.log(output)
    document.getElementById("postAnimal").innerHTML = output;
    } 
};
xhr.open("GET", Reptiles, true);
xhr.send();



$('#txt-search').keyup(function(){
    var searchField = $(this).val();
    if(searchField === '')  {
        $('#filter-records').html('');
        return;
    }
    
    var regex = new RegExp(searchField, "i");
    var output = '<div class="row">';
    var count = 1;
      $.each(Reptiles, function(key, val){
        if ((val.friendlyName.search(regex) != -1) || (val.scientificName.search(regex) != -1)) {output = `
        <ul id="list">
            <li id="name">${response.friendlyName}</li><br>
            <li><img src='${response.picturePath}.jpg'</li><br>
            <li><span>Scientific Name: </span>${response.scientificName}</li>
            <li><span>Description: </span>${response.description}</li><br>
            <li><span>Life History: </span>${response.lifeHistory}</li><br>
            <li><span>Habitat: </span>${response.habitat}</li><br>
            <li><span>Distribution: </span>${response.distribution}</li>
            <li><span>Source: </span><a href="${response.url}">Site</a></li>
        </ul>;
        `
          if(count%2 == 0){
            output += '</div><div class="row">'
          }
          count++;
        }
      });
      output += '</div>';
      $('#filter-records').html(output);
});

enter image description here

Источник
wazz
9 августа 2021 в 09:34
0

Другой подход заключается в фильтрации HTML-кода, который уже находится на странице. С каждым нажатием клавиши вы можете искать <li> или id или имена или что угодно, и показывать или скрывать соответствующие элементы. Поскольку у вас есть доступ к HTML-коду, создающему страницу, вы можете добавить настраиваемые атрибуты, облегчающие поиск.

Ответы (2)

avatar
Felipe Ceballos
11 августа 2021 в 02:49
0

С некоторой помощью мне удалось заставить его работать.

const xhr = new XMLHttpRequest();
const Reptiles = "ReptilesTX.json";

var dataFromServer = [];

xhr.onload = function() {
if (this.readyState == 4 && this.status == 200) {
    var response = JSON.parse(this.responseText);
    dataFromServer = response;
    let output = '';
    for(let i = 0; i < response.length; i++){

        output +=  `
    <ul id="list">
        <li id="name">${response[i].friendlyName}</li><br>
        <li><img src='${response[i].picturePath}.jpg'</li><br>
        <li><span>Scientific Name: </span>${response[i].scientificName}</li>
        <li><span>Description: </span>${response[i].description}</li><br>
        <li><span>Life History: </span>${response[i].lifeHistory}</li><br>
        <li><span>Habitat: </span>${response[i].habitat}</li><br>
        <li><span>Distribution: </span>${response[i].distribution}</li>
        <li><span>Source: </span><a href="${response[i].url}">Site</a></li>
    </ul>;
    `
    }
    //console.log(output)
    document.getElementById("postAnimal").innerHTML = output;
    } 
};
xhr.open("GET", Reptiles, true);
xhr.send();



$('#txt-search').keyup(function(){
    var searchField = $(this).val();
    if(searchField === '')  {
        $('#filter-records').html('');
        return;
    }
    
    var regex = new RegExp(searchField, "i");
    var output = '<div class="row">';
    var count = 1;
    console.log({dataFromServer})
      $.each(dataFromServer, function(key, val){
          console.log({key, val})
        if ((val.friendlyName.search(regex) != -1) || (val.scientificName.search(regex) != -1)) {output = `
        <ul id="list">
            <li id="name">${val.friendlyName}</li><br>
            <li><img src='${val.picturePath}.jpg'</li><br>
            <li><span>Scientific Name: </span>${val.scientificName}</li>
            <li><span>Description: </span>${val.description}</li><br>
            <li><span>Life History: </span>${val.lifeHistory}</li><br>
            <li><span>Habitat: </span>${val.habitat}</li><br>
            <li><span>Distribution: </span>${val.distribution}</li>
            <li><span>Source: </span><a href="${val.url}">Site</a></li>
        </ul>;
        `
          if(count%2 == 0){
            output += '</div><div class="row">'
          }
          count++;
        }
      });
      output += '</div>';
      $('#postAnimal').html(output);
});

avatar
wazz
9 августа 2021 в 10:05
1

Это базовый поиск, который показывает и скрывает HTML. Прямо сейчас он показывает/скрывает элементы списка, но вы можете обернуть каждое животное в div с идентификатором и выполнить поиск по нему.

Кроме того, поиск осуществляется только по целым словам, но вы можете настроить поиск по каждой букве и скрывать все больше и больше животных по мере того, как поиск становится более конкретным.

function doFilter() {

  var searchInput = document.getElementById("searchInput").value;

  $("li").filter("li[data-" + searchInput + "]")
    .css("display", "block");

  $("li").not("li[data-" + searchInput + "]")
    .css("display", "none");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Enter one of the animals on the list, without 'data-'.<br />
The whole word must be entered.<br /><br />

<input id="searchInput" type="text" onkeyup="doFilter()" />

<ul>
  <li data-aardvark>aardvarks eat ants...</li>
  <li data-kangaroo>what's that kangaroo doing here?</li>
  <li data-lizard>lizards are cold...</li>
  <li data-alligator>gators play football...</li>
</ul>