对于包含许多行的表,html多级展开折叠很慢

时间:2013-09-17 23:00:01

标签: javascript jquery html

html表在树类型视图中有4个层次结构。要为用户提供扩展/折叠到任何级别的控件,请使用以下函数。 但是这个函数在IE8上执行需要6秒以上。 Chrome需要一半的时间。有关如何加快此功能的任何建议?感谢

function showDetailLevel(level) {
    /*hide all the tr*/
    $('.dataRow').each(function() {
        $(this).hide();
    });
    /*collapse all the carets*/
    $('.detailsCarat').each(function() {
        if ($(this).hasClass('ui-icon-triangle-1-s')) {
            $(this).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
        }                       
    }); 
    /*show the rows and expand all the carets that are at a tree level above the selected level*/
    for (var i=1; i<=level;i++) {   
        $('.detailLevel'+i).each(function() {
            $(this).show();
            if (i<level) {
                $(this).find('span.ui-icon-triangle-1-e').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
            }
        }); 
    }   
}

2 个答案:

答案 0 :(得分:1)

上述脚本中有几种性能损失。只有CSS类名的jQuery选择器和许多类名的不需要的切换会立即跳出来。

在选择类名($('tr.dataRow').each...)时也使用标记名称。

除非我们考虑使用标记名称,否则每个语句都是不必要的,但可能不会比更简洁的脚本慢得多:

$('tr.dataRow').hide();

/*collapse all the carets*/
$('span.detailsCarat').toggleClass('ui-icon-triangle-collapsed');

更重要的是,尽可能切换单个类名以避免重排(When does reflow happen in a DOM environment?)。这是关键。您的HTML应该以这样的方式嵌套:您可以在容器元素中切换单个CSS类,并利用CSS选择器来完成所需的一切:隐藏,显示和更改外观。例如,适用于'ui-icon-triangle-1-s'的任何样式规则都应该在包含div.container.active .ui-icon-triangle-1等选择器的规则中。

答案 1 :(得分:1)

我会为初学者尝试以下方法:将父div添加到#YOURCONTAINERDIV所指出的那些类中。我还为你的添加/删除类添加了toggleClass。

我对这行代码感到好奇:你能解释为什么级别的循环,然后通过'.detailLevel'+ i的集合做一个.each。我认为你的问题很多。

for (var i=1; i<=level;i++) { 
    $('.detailLevel'+i).each(function() {
        $(this).show();

 function showDetailLevel(level) {
      /*hide all the tr*/
         $('#YOURCONTAINERDIV .dataRow').each(function() {
         $(this).hide();
});
/*collapse all the carets*/
$('#YOURCONTAINERDIV.detailsCarat').each(function() {
    if ($(this).hasClass('ui-icon-triangle-1-s')) {
        $(this).removeClass('ui-icon-triangle-1-s').toggleClass( ui-icon-triangle-1-e, ui-icon-triangle-1-s );                    
}); 
/*show the rows and expand all the carets that are at a tree level above the selected level*/
for (var i=1; i<=level;i++) {
    // I suspect a big issue is here as you are looping, then looping again thru
    // a collection of elements. 
    $('.detailLevel'+i).each(function() {
        $(this).show();
        if (i<level) {
            $(this).find('span.ui-icon-triangle-1-e').toggleClass( ui-icon-triangle-1-e, ui-icon-triangle-1-s );
        }
    }); 
}   

}