Как объединить дополнительные js, чтобы, возможно, выделить текстовые тесты, отфильтрованные по таблице? - PullRequest
0 голосов
/ 05 июля 2019

HTML

<input id="myInput" type="text" onkeyup="ContactsearchFX()" 
       placeholder="Search Titles">
    *</p>
<table id="myTable" style="width: 100%" class="style1">

JAVASCRIPT

window.onload = function() {
   var rows = document.querySelectorAll('tr');

   for (var i = 0; i < rows.length; i++) {
    rows[i].style.display = 'none';
   }
 }

function ContactsearchFX() {
  var input, filter, table, tr, td, i;

   input = document.getElementById("myInput");

  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
     if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
     } else {
       tr[i].style.display = "none";

      }
    }
  }

   var rows = document.querySelectorAll('tr');

   if (input.value.length == 0) {
    for (var i = 0; i < rows.length; i++) {
      rows[i].style.display = 'none';
    }
  }
}

Пытались внедрить https://markjs.io/ среди других различных основных решений без каких-либо исправлений или решений.Надеюсь, достаточно информации, чтобы продолжить.Пожалуйста, спросите, если вам нужно больше деталей.

1 Ответ

0 голосов
/ 06 июля 2019

Setup

Судя по коду, которым вы поделились, вы, вероятно, не используете es6 или js bundler для настройки вашего проекта.Это означает, что import s и библиотека <scrpit> s не попадут внутрь ваших index.html

шагов

  1. Убедитесь, что вы правильно загружаете скрипт
  2. Очиститевверх по коду
    • разделите его на куски, чтобы лучше понять, что происходит не так
  3. Обновите код с помощью функции выделения, описанной при «запуске» пакета

Примечания

С библиотекой mark.js было бы лучше очистить отметку (.unmark()) перед повторным ее применением.потому что это добавит больше элементов при каждом изменении.Вот почему мы сохраняем один экземпляр метки для контекста (контекст - это элемент таблицы) вместо того, чтобы создавать новый экземпляр внутри highlightChanges функции

Фрагмент, приведенный ниже, не является оптимальной реализацией этой функциональности, но можетслужить отправной точкой.Он был основан на оригинальном коде

Snippet с добавленной подсветкой

var input, table, rows, markInstance;

window.onload = function init() {
  input = document.getElementById("myInput");
  table = document.getElementById('myTable');
  rows = table.querySelectorAll('tr');
  markInstance = new Mark(table);

  clear();
}

function ContactsearchFX() {

  clear();

  if (input.value.length == 0) return;

  filterRows(input.value);
  highlightMatches(input.value);
}

function clear() {
  markInstance.unmark();
  
  for (var i = 0; i < rows.length; i++) {
    rows[i].style.display = 'none';
  }
}

function filterRows(text) {
  var part = text.toUpperCase();

  for (i = 0; i < rows.length; i++) {
    var row = rows[i];
    var td = row.getElementsByTagName("td")[0];

    if (td) {
      // part = GI
      // innerHtml = <MARK DATA-MARKJS="TRUE">G</MARK>ITHUB (wont match)
      // innerText = GITHUB (will match)
      var content = td.innerText.toUpperCase();

      if (content.includes(part)) {
        row.style.display = "";
      }
    }
  }
}

function highlightMatches(text) {
   markInstance.mark(text);
}
.input-wrap {
  margin-bottom: 12px;
}

.hints {
  display: none;
  margin-top: 12px;
}

#myInput:invalid~.hints {
  display: block;
}

mark {
    background: orange;
    font-weight: bold;
    color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.js"></script>

<div class="input-wrap">
  <label>
    Search Titles: 
    <input id="myInput" type="text" required 
           onkeyup="ContactsearchFX()" 
           placeholder="Search Titles" />

    <span class="hints">
      Hints: type "git", "bit", "forge" ...
    </span>
  </label>
</div>

<table id="myTable" style="width: 100%" class="style1">
  <tr>
    <th>Title</th>
    <th>Description</th>
  </tr>
  <tr>
    <td>Github</td>
    <td>Is the HUB</td>
  </tr>
  <tr>
    <td>Gitlab</td>
    <td>Have nice CI</td>
  </tr>
  <tr>
    <td>Bitbucket</td>
    <td>Has Jira integration (Duh)</td>
  </tr>
  <tr>
    <td>SourceForge</td>
    <td>Open source projects live here. It is said</td>
  </tr>
</table>

И более подходящая версия для производства

Быстрый просмотр примеров и API для параметра options параметраmark() обзор функции, что мы можем заменить большую часть логики хуками из options

Обработчик события ввода debounce ed (функция из lodash _.debounce), таким образомфильтрация начнется, когда пользователь перестанет набирать (более 250 мс)

Контент снова .unmark() редактируется в начале - другая часть заключается в том, что мы используем параметр options с обратным вызовом done для продолженияhighlightMatches когда unmark заканчивает

Параметр options имеет опцию each, которая является обратным вызовом для каждого соответствующего элемента.Используя этот обратный вызов, мы можем искать его родителя, который, как мы знаем, должен быть строкой, и мы добавляем класс show, чтобы строка могла стать видимой.

Также существует noMatch prop, который будет вызываться (назад) если тексты ничего не соответствуют, поэтому мы можем показать некоторую подсказку, возможно, попробовать другой текст

Параметр options содержит другие полезные реквизиты, которые могут настраивать сопоставление, например, подстановочные знаки, сопоставление с учетом регистра и т. д.

var input, table, rows, noMatches, markInstance;

window.onload = function init() {
  input = document.getElementById('myInput');
  noMatches = document.getElementById('noMatches');
  table = document.getElementById('myTable');
  rows = table.querySelectorAll('tr');
  markInstance = new Mark(table);

  input.addEventListener('keyup', _.debounce(ContactsearchFX, 250));
}

function ContactsearchFX() {

  resetContent();

  markInstance.unmark({
    done: highlightMatches
  });

}

function resetContent() {
 noMatches.textContent = '';

  rows.forEach(function(row) {
    row.classList.remove('show');
  });
}

function highlightMatches() {
  markInstance.mark(input.value, {
    each: showParantRow,
    noMatch: onNoMatches,
  })
}

function showParantRow(element) {
  var row = element.closest('tr');
  row.classList.add('show');
}

function onNoMatches(text) {
  noMatches.textContent = 'No records match: "' + text + '"';
};
.input-wrap {
  margin-bottom: 12px;
}


#myInput:invalid~.hints {
  display: block;
}

#noMatches:empty, #noMatches:empty + .hints {
  display: none;
}

.filterTable tr {
  display: none;
}

.filterTable .show {
  display: table-row;
}

mark {
  background: orange;
  font-weight: bold;
  color: black;
}
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>

<div class="input-wrap">
  <label>
    Search Titles: 
    <input id="myInput" type="text" required
           placeholder="Search Titles" />
  </label>
</div>

<div class="hintsWrap">
  <p id="noMatches"></p>
  <p class="hints">
    Hints: type "git", "bit", "forge" ...
  </p>
</div>


<table id="myTable" style="width: 100%" class="filterTable">
  <tr>
    <td>Github</td>
    <td>Is the HUB</td>
  </tr>
  <tr>
    <td>Gitlab</td>
    <td>Have nice CI</td>
  </tr>
  <tr>
    <td>Bitbucket</td>
    <td>Has Jira integration (Duh)</td>
  </tr>
  <tr>
    <td>SourceForge</td>
    <td>Open source projects live here. It is said</td>
  </tr>
</table>
...