功能很慢,有更快的方法吗?(使用jQuery 1.4.2)

Ste*_*ven 3 performance jquery html-table

以下功能至少需要3秒才能运行(在500个表行上).是否可以更快地完成此功能?

function prepareTable() {
    var groupIndex = 0;
    $("#row tbody tr").each(function(index) {
    // each row gets a unique id
    // remove default css styles for table rows
    // read out hidden value, that stores if row is a group
    var group = $(this).attr('id', 'node-'+index).removeClass("odd event").find('td :hidden').attr('value');
    // if it is a group, add special styles to row and remember row index
    if (group == 'true') {
        groupIndex = index;
        $(this).addClass('odd').find("td:first")
            .mouseenter(function() {
                $(this).parent().addClass("swGroupLink");
            })
            .mouseleave(function() {
                $(this).parent().removeClass("swGroupLink");
        });
    } else {
        // make all following rows to children of the previous group found
        $(this).addClass('even child-of-node-' + groupIndex);
    }   
    });
}
Run Code Online (Sandbox Code Playgroud)

jAn*_*ndy 6

我建议两个改进:

  • 高速缓存 DOM References
  • 在你的餐桌工作离线

function prepareTable() {
   var groupIndex = 0;
   var $mytable = $('#row'),
       $parent  = $mytable.parent();

   $mytable = $mytable.detach();

   $mytable.find('tr').each(function(index) {
      var $this = $(this);
      var group = $this.attr('id', 'node-'+index).removeClass("odd event").find('td :hidden').attr('value');
// if it is a group, add special styles to row and remember row index
   if (group == 'true') {
       groupIndex = index;
       $this.addClass('odd').find("td:first")
           .mouseenter(function() {
               $this.parent().addClass("swGroupLink");
           })
           .mouseleave(function() {
               $this.parent().removeClass("swGroupLink");
       });
   } else {
       // make all following rows to children of the previous group found
       $this.addClass('even child-of-node-' + groupIndex);
   }   
   });

   $parent.append($mytable);
}
Run Code Online (Sandbox Code Playgroud)

我添加了一个在循环$this中缓存的变量.我还添加了和.存储元素并存储父节点.那是因为我从DOM中删除了整个元素,完成了工作并将其重新附加到父级.$(this).each()$mytable$parent$mytable#row$parent#row

测试环境:http://www.jsfiddle.net/2C6fB/4/

如果仍然太慢,那么你还有其他选择.首先,看看你是否可以将循环分成更小的部分.例如,您可以通过使用asychronous回调来进行大量优化setTimeout.这可能是一个棘手的业务,我需要更详细地了解您的代码,但一般来说,您可能只想将整个循环包装成单个setTimeout()函数.示例 - > http://www.jsfiddle.net/2C6fB/5/

这可确保浏览器在操作时不会"挂起".但是,当然这需要更长的时间来完成整个任务.