效率低下我的意思是,激活代碼會使頁面掛起20多秒。HTML表格上的Javascript/jquery過濾器效率極低
要設置場景,我目前有一個如下所示的HTML表格。它可以相當大,容易1,000-1,500行和40列寬。它是從Python/Flask生成的靜態HTML表格,然後JavaScript接管允許用戶過濾和排序行。我使用jquery tablesorter小部件來允許用戶按他們希望的任何列對行進行排序。
表本身具有如下的結構:
<table id="myTablePlayers" class="tablesorter table table-striped table-bordered table-hover" style="overflow: visible">
<thead>
<tr>
<th>...</th>
<th>...</th>
<th>...</th>
<th>...</th>
...
<th>...</th>
</tr>
</thead>
<tbody>
<tr class="playerData">
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
...
<td>...</td>
</tr>
...
</tbody>
</table>
用戶給出的過濾器如下所示:
- 最低GP - 輸入字段刪除比用戶在輸入更少的所有行特定列
- 組 - 選擇刪除特定列中不匹配的所有行的字段(文本)
- 位置 - 選擇字段(文本)刪除特定列中不匹配的所有行
- age - 輸入字段,用於刪除特定列中的用戶輸入以下的所有行(例如,如果輸入20,將保持所有行與年齡範圍爲[20.0,21.0)
的JavaScript/jQuery的我已經寫了,很可能是罪魁禍首如下:
function autoRank() {
// auto number
rank = 0;
$("#myTablePlayers .playerData").each(function() {
if ($(this).css("display") != "none") {
rank++;
$(this).find('td').eq(colRank).text(rank);
}
});
}
function filterTable() {
// Need some error checking on input not number
minGP = $("#mingp").val()
teams = $("#teamFilter").val()
position = $("#position").val()
age = $("#age").val()
$("#myTablePlayers .playerData").show();
$("#myTablePlayers .playerData").each(function() {
toHide = false;
if (teams != "") {
if (!$(this).find('td').eq(colTeam).text().toUpperCase().includes(teams.toUpperCase())) {
toHide = true;
}
}
if (Number($(this).find('td').eq(colGP).text()) < minGP) {
toHide = true;
}
if (position != "") {
if (position == "D") {
if ($(this).find('td').eq(colPos).text().indexOf("D") == -1) {
toHide = true;
}
} else if (position == "F") {
if ($(this).find('td').eq(colPos).text().indexOf("D") != -1) {
toHide = true;
}
} else if ($(this).find('td').eq(colPos).text() != position) {
toHide = true;
}
}
if (age != "") {
column = Number($(this).find('td').eq(colAge).text())
age = Number(age)
if ( column < age || column >= age+1 ) {
toHide = true;
}
}
if (toHide == true) {
$(this).hide();
}
});
autoRank();
}
$("#teamFilter").on('change', filterTable);
$("#mingp").on('change', filterTable);
$("#position").on('change', filterTable);
$("#age").on('change', filterTable);
什麼這種代碼會導致瀏覽器掛起效率低下?我應該改變什麼才能使其高效?
我看着谷歌,但jQuery的表濾波器插件不給我來過濾基於如上(例如https://www.sitepoint.com/12-amazing-jquery-tables/)概述了具體的投入特定的列行的能力。
你有沒有基準把那麼多元素放入沒有javascript的DOM?我認爲這可能會強調瀏覽器只是HTML元素。 – Victory
這可能有助於提高代碼的性能。 [什麼是最快的兒童()或發現()在jQuery?](http://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery) – legitghost
看看www .datatables.net jquery插件它比jquery小部件更健壯。 – Bindrid