什么'这是用javascript隐藏和显示表中所有行的最快方法

What's the fastest way of hiding and showing all the rows of a table in javascript?

本文关键字:方法 显示 隐藏 javascript 什么      更新时间:2023-09-26

我正在构建一个用于查询html表(10k行以上)的过滤器。我最初的想法是首先隐藏所有行,然后取消隐藏与特定查询匹配的行。如果过滤器已删除,则显示所有行。

这是编写隐藏/显示所有行函数的最佳方式吗?

// optimize this!
this.hideAllRows = function() {
    nodes = document.getElementById('table_body').children
    for(var i=0, i_max=nodes.length; i<i_max; i++) {
        nodes[i].style.display="none"
    }
}
// optimize this!
this.showAllRows = function() {
    nodes = document.getElementById('table_body').children
    for(var i=0, i_max=nodes.length; i<i_max; i++) {
        nodes[i].style.display=""
    }
}

谢谢!

一种解决方案是实现分页或"无限"滚动功能。这将消除同时渲染10k个dom元素的需要。您可以在用户滚动时批量呈现它们,或者将它们分块到页面中。

或者,您可以尝试将表从dom中拉出,隐藏行,然后重新插入。这将防止不必要的回流/绘制等。

根据经验,使用纯javascript for循环比使用jQuery .each()更快,但使用.getElementById().children属性的基本选择已经得到了很好的优化。

然而,在浏览器中迭代10k以上的元素总是很慢。显示和隐藏元素最适合100年代而不是1000年代的唱片集。

为什么不发出AJAX请求,返回已经格式化为<tr>...some <td>s here....</tr><tr>...some <td>s here....</tr>的数据(可能来自数据库)?

这样,当涉及到过滤时,您可以让数据库承担所有繁重的工作,它们经过了优化。它使您的代码保持简单,带宽减少,DOM操作保持在最低限度。

只要您想应用筛选器,就可以发出$.ajax请求。

function filter(criteria){
    $.ajax({
        url : myDataUrl,
        type : "POST",
        data : {criteria : criteria}
    })
    .success(function (data){
        $("#table-body").html(data);
    });
}