这个问题并不是在寻求特定问题的解决方案,而是试图了解为什么Safari在这种情况下效率低下。当我谈到极慢时,代码在Firefox和Chrome中运行时间不到1秒,而在Safari中需要30-90秒的范围内。这可能已经是一个记录下来的问题,但我不知道原因。
情况是我有一个相当大的HTML表格。它大约有1,000-1,500行,40列宽。结构看起来像这样:
情况是我有一个相当大的HTML表格。它大约有1,000-1,500行,40列宽。结构看起来像这样:
<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>
许多表单字段允许用户选择和输入信息以帮助过滤行。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);
当我开始精简代码时,无论循环内部包含什么内容,导致运行时间过长的有问题的代码似乎是$("#myTablePlayers .playerData").each(function() {...
我通过使用原生JS重新编写代码来解决了这个问题,但这并不能解释为什么这段代码在一个浏览器中如此低效。
.each()
,而在于你通过.css()
检查布局的方式。 - Pointylet
或var
来声明你的本地变量。 - Pointy$("#teamFilter").on('change', filterTable);
以及其他一些方法,然后在filterTable
中,相同的元素上调用了.val()
方法。我想知道是否jQuery在内部触发了change
事件,从而导致了大量的递归。 - user1106925