Есть несколько вещей, которые вы можете сделать, чтобы улучшить производительность ...
- Не используйте
.innerHTML
, когда текст, с которым вы работаете, не содержит HTML, потому что браузер задействуетHTML-парсер каждый раз, когда вы используете это.Для получения / настройки текста, который не содержит HTML, используйте .textContent
.В JQuery аналогичными методами являются .html()
и .text()
. - Не сканируйте DOM на наличие элементов, которые вы уже сканировали ранее.Это означает, что кешированные переменные ссылаются на ваши DOM-объекты вне ваших многократно вызываемых функций.
- Вместо того, чтобы циклически обрабатывать каждую строку и ячейку вручную, и, поскольку вы используете JQuery, просто поместите все строки в упакованный набор JQuery.и работать с этой коллекцией.Используйте метод JQuery
.find()
с селектором JQuery :contains
.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
#demo { margin-top:1em; padding:3px; width:20%; font-weight:bold;
border:1px solid #aa0; background:#ee3; height:1em;
}
</style>
</head>
<body>
<input type="text" id="myInput">
<table id="tabella">
<thead>
<tr>
<th>TIPO</th>
<th>SCHEMA</th>
<th>NOME</th>
<th>DDL</th>
</tr>
</thead>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 21</td>
<td>row 1, cell 3</td>
<td>row 1, cell 4</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 21</td>
<td>row 2, cell 3</td>
<td>row 2, cell 4</td>
</tr>
<tr>
<td>row 3, cell 1</td>
<td>row 3, cell 21</td>
<td>row 3, cell 3</td>
<td>row 3, cell 4</td>
</tr>
<tr>
<td>row 4, cell 1</td>
<td>row 4, cell 21</td>
<td>row 4, cell 3</td>
<td>row 4, cell 4</td>
</tr>
</table>
<div id="demo"></div>
<script>
// Get your DOM references outside of the callback function
// so that you aren't scanning the DOM over and over for the
// same elements.
let $tbl = $("#tabella");
let $dem = $("#demo");
// Don't use inline HTML event handlers (i.e. oninput).
// Do all of yor JavaScript outside of the HTML
$("#myInput").on("input", myFunction);
function myFunction() {
// Hide all the rows in the table, except the header row
// (<tbody> is implicitly created)
$("tbody > tr",$tbl).hide();
// Then, find the row(s) that contain the entered text and show only them.
let $found = $tbl.find("tbody > tr:contains('" + this.value + "')").show();
// Don't use .innerHTML for non-HTML strings, use .textContent instead.
// In JQuery, that's .text() instead of .html()
$dem.text($found.length + " records found.");
}
</script>
</body>
</html>