目前正在使用此 javascript 函数通过匹配 2 个不同表格中的高度来对齐所有行。每个表都有 1000 多行。而这个函数的执行时间超过 4 秒。有没有更快的方法来匹配两个不同表格的行高?谢谢
function alignTableRowHeights() {
$('#table1 tr').each(function(i) {
var rowDisplay=$(this).css("display")
if(rowDisplay!="none"){
// Row is visible
var tableTwoRow = $('#table2 tr').get(i);
var height = $(tableTwoRow).height();
$(this).height(height);
}
});
}
表格中的行的高度并不完全相同。因此需要有逻辑来单独获取每一行的高度。并且某些行可能被隐藏(用于展开和折叠),因此需要检查行是否显示。目的是并排显示两个表格,以便可见行需要保持同步和对齐。
最佳答案
只有 Javascript 才是最快的,然而,最慢的部分可能不是 jQuery 本身,而是你如何使用它:
- 对于每一行,您查询所有其他行只是为了使用一个。解决方案:在该表的循环之前获取查询结果
- 对于您要求从计算样式中提取显示属性的每一行。解决方案:使用 jQuery 的
:visible
选择器,这样您就不必执行单独的检查。 - 有时在表格可见时操作 DOM 可能会非常慢,具体取决于您的布局、样式等。解决方案:从 dom 中删除您正在更新的表格,更新高度,然后将其放回原处。
下面是我可能会这样做的方法:
function alignTableRowHeights() {
// copy the heights into an array
var heights = [];
$('#table2').find('tr:visible').each(function(i) {
heights[i] = $(this).height();
});
// get visible table one rows before we remove it from the dom
var tableOneRows = $('#table1').find('tr:visible');
// remove table one from the dom
var tempDiv = $('<div />');
var table1 = $('#table1');
table1.replaceWith(tempDiv);
$.each(tableOneRows, function(i) {
$(this).height(heights[i]);
});
// put table one back in the dom
tempDiv.replaceWith(table1);
}
关于javascript - 在 2 个不同的表中对齐行高的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691517/