Фильтрация таблицы по имени элемента - PullRequest
3 голосов
/ 08 марта 2020

Я пытаюсь отфильтровать эту таблицу HTML, написав какой-то текст в форме поиска, что прекрасно работает, но всякий раз, когда он фильтрует, элементы пытаются заполнить всю ширину таблицы вместо сохранения их первоначальной ширины элемента ( 25% ширины таблицы, без учета пробелов между ячейками).

function searchFilter () {
   const input = document.getElementById('myInput');
   const filter = input.value.toUpperCase();
   const table = document.getElementById('tablaPiola');
   const articule = table.getElementsByTagName('td');

   for (i = 0; i < articule.length; i++) {
      a = articule[i].getElementsByTagName("a")[0];
      txtValue = a.textContent || a.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
         articule[i].style.display = "";
         } else {
         articule[i].style.display = "none";
         }
   }
}

document.getElementById("filter-btn").addEventListener("click", searchFilter);
body {
background-color: black;
}

table
{border-spacing: 20px;
table-layout: fixed;
width: 600px;
margin: auto;
margin-top: 10px;}

td
{text-align: center;
border-radius: 10px;}

td a
{width: 100%;
display: block;
line-height: 50px;
text-decoration: none;
font-family: "Poppins";
font-weight: 700;
font-size: 12px;
color: white;}

.automatizaciones
{background-image: url("https://via.placeholder.com/100/0000FF/0000FF");
background-size: cover;}

.bpm_a_ms
{background-image: url("https://via.placeholder.com/100/0000FF/0000FF");
background-size: cover;}

.compresion
{background-image: url("https://via.placeholder.com/100/0000FF/0000FF");
background-size: cover;}

.compresion_multibanda
{background-image: url("https://via.placeholder.com/100/0000FF/0000FF");
background-size: cover;}
<input type="text" id="myInput">
<input type="button" id="filter-btn" value="Apply">
<table class="tabla_basico" id="tablaPiola">
   <tr>
      <td class="automatizaciones">
         <div class="overlay_basico"><a href="/">AUTOMATIZACIONES</a></div>
      </td>
      <td class="bpm_a_ms">
         <div class="overlay_intermedio"><a href="/">BPM A MS</a></div>
      </td>
      <td class="compresion">
         <div class="overlay_basico"><a href="compresion.html">COMPRESIÓN</a></div>
      </td>
      <td class="compresion_multibanda">
         <div class="overlay_intermedio"><a href="/">COMPRESIÓN MULTIBANDA</a></div>
       </td>
   </tr>
</table>

Это моя веб-страница

Вот как она фильтрует

1 Ответ

2 голосов
/ 08 марта 2020

Первоначально я думал, что visibility: hidden, но вы указали, что это означает, что те, которые отображаются, больше не слева.

Моя единственная другая мысль - добавление ячеек заполнения в конце:

function searchFilter () {
   const input = document.getElementById('myInput');
   const filter = input.value.toUpperCase();
   const table = document.getElementById('tablaPiola');
   // Remove any fillers we added last time
   table.querySelectorAll(".filler").forEach(filler => {
       filler.parentNode.removeChild(filler);
   });
   const articule = table.getElementsByTagName('td');
   // Remember how many are showing at the end
   let showing = 0;

   for (i = 0; i < articule.length; i++) {
      a = articule[i].getElementsByTagName("a")[0];
      txtValue = a.textContent || a.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
         articule[i].style.display = "";
         ++showing; // Remember we're showing this one
      } else {
         articule[i].style.display = "none";
      }
   }
   // Grab the length (since `articule` is a live list
   const max = articule.length;
   // Add blank cells to the end
   while (showing < max) {
      const filler = document.createElement("td");
      filler.className = "filler";
      table.appendChild(filler);
      ++showing;
   }
}

Live Пример:

function searchFilter () {
   const input = document.getElementById('myInput');
   const filter = input.value.toUpperCase();
   const table = document.getElementById('tablaPiola');
   // Remove any fillers we added last time
   table.querySelectorAll(".filler").forEach(filler => {
       filler.parentNode.removeChild(filler);
   });
   const articule = table.getElementsByTagName('td');
   // Remember how many are showing at the end
   let showing = 0;
   
   for (i = 0; i < articule.length; i++) {
      a = articule[i].getElementsByTagName("a")[0];
      txtValue = a.textContent || a.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
         articule[i].style.display = "";
         ++showing; // Remember we're showing this one
      } else {
         articule[i].style.display = "none";
      }
   }
   // Grab the length (since `articule` is a live list
   const max = articule.length;
   // Add blank cells to the end
   while (showing < max) {
      const filler = document.createElement("td");
      filler.className = "filler";
      table.appendChild(filler);
      ++showing;
   }
}

document.getElementById("filter-btn").addEventListener("click", searchFilter);
body {
background-color: black;
}

table
{border-spacing: 20px;
table-layout: fixed;
width: 1200px;
margin: auto;
margin-top: 100px;}

td
{text-align: center;
border-radius: 10px;}

td a
{width: 100%;
display: block;
line-height: 150px;
text-decoration: none;
font-family: "Poppins";
font-weight: 700;
font-size: 17.5px;
color: white;}

.automatizaciones
{background-image: url(imagenes/basico/automatizaciones/articulo.jpg);
background-size: cover;}

.bpm_a_ms
{background-image: url(imagenes/intermedio/bpm_a_ms/articulo.jpg);
background-size: cover;}

.compresion
{background-image: url(imagenes/basico/compresion/articulo.jpg);
background-size: cover;}

.compresion_multibanda
{background-image: url(imagenes/intermedio/compresion_multibanda/articulo.jpg);
background-size: cover;}
<input type="text" id="myInput">
<input type="button" id="filter-btn" value="Apply">
<table class="tabla_basico" id="tablaPiola">
   <tr>
      <td class="automatizaciones">
         <div class="overlay_basico"><a href="/">AUTOMATIZACIONES</a></div>
      </td>
      <td class="bpm_a_ms">
         <div class="overlay_intermedio"><a href="/">BPM A MS</a></div>
      </td>
      <td class="compresion">
         <div class="overlay_basico"><a href="compresion.html">COMPRESIÓN</a></div>
      </td>
      <td class="compresion_multibanda">
         <div class="overlay_intermedio"><a href="/">COMPRESIÓN MULTIBANDA</a></div>
       </td>
   </tr>
</table>

Некоторые другие примечания, не связанные непосредственно с основной проблемой:

  • Этот код выпадает жертва того, что я называю Ужас неявных глобалов . Вы никогда не объявляете i, a или txtValue, поэтому вы в конечном итоге создаете глобальные переменные, когда назначаете их. Я рекомендую использовать строгий режим во всем коде, чтобы при попытке сделать это вы получили ошибку.

  • FWIW, я вижу, вы используете функции ES2015 + (const, например), так что вы могли бы использовать for-of l oop вместо for l oop. for-of немного меньше печатает. Но на некоторых платформах вам может понадобиться многократное использование итерации. Мой ответ здесь показывает, как это сделать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...