【问题标题】:DOM selection in jqueryjQuery中的DOM选择
【发布时间】:2010-11-01 19:02:37
【问题描述】:

我有一张桌子,我做了排序。它的执行时间不好。我猜这是因为 DOM 操作。 /* 我正在转换为数组 */

var rows = $table.find('tbody > tr').get(); 


 $.each(rows, function(index, row){     /*then again to 2D array */

            if(($(row).children('td').eq(0).attr('class').indexOf('collapse') != -1 || $(row).children('td').eq(0).attr('class').indexOf('expand') != -1)){ 
                myData.push(myData1);
                myData1 = [];
            }
                myData1.push(row);  
                rowCount++;
                if(rowCount == $(rows).length){ // to assign last group of rows
                myData.push(myData1);
                    myData1 = [];

            }
   });

这是直接通过数组选择DOM元素的最佳方式。因为我用了很多次。

【问题讨论】:

标签: jquery arrays dom


【解决方案1】:

嗯,您可以立即做一件事,这可能会提高性能:

你看到你必须得到该行的第一个<td> 的类值的长链了吗?你正在做完全相同的,长链,链两次。试试

// then again to 2D array
$.each(rows, function(index, row) {
    var classes = $(row).children('td').eq(0).attr('class')
    if((classes.indexOf('collapse') != -1 || classes.indexOf('expand') != -1)){ 
        myData.push(myData1);
        myData1 = [];
    }
    myData1.push(row);
    rowCount++;
    if(rowCount == $(rows).length){ // to assign last group of rows
        myData.push(myData1);
        myData1 = [];
    }
});

如果$.each() 函数运行很多次,这应该至少可以为您节省一些。

【讨论】:

  • 谢谢 Tomas,有没有 $.each() 的替代函数
  • 很难说是否有,不知道你实际上想要完成什么。也请参阅 Adrian 的建议 - 如果您同时实现这两个功能,性能是否足够好?
【解决方案2】:

您也可以尝试使用 hasClass 函数,并使用 :first 选择器而不是返回所有 tds 然后只取第一个:

if( ($(row).children('td:first').hasClass('collapse')) || ($(row).children('td:first').hasClass('expand')) {

【讨论】:

    猜你喜欢
    • 2015-03-11
    • 2014-08-12
    • 2018-11-03
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    相关资源
    最近更新 更多