本文介绍了基于数值属性的DOM元素更有效的jQuery排序方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些简单的jQuery,用于根据数值属性对某些元素进行排序,如 http://jsfiddle.net/MikeGrace/Vgavb/

I have some simple jQuery written to sort some elements based on a numerical attribute as illustrated at http://jsfiddle.net/MikeGrace/Vgavb/

// get array of elements
var myArray = $("#original div");

// sort based on timestamp attribute
myArray.sort(function (a, b) {

    // convert to integers from strings
    a = parseInt($(a).attr("timestamp"), 10);
    b = parseInt($(b).attr("timestamp"), 10);

    // compare
    if(a > b) {
        return 1;
    } else if(a < b) {
        return -1;
    } else {
        return 0;
    }
});

// put sorted results back on page
$("#results").append(myArray);

它工作正常,但我认为它不会扩展,因为总共进行了185个jQuery调用,其中184个正在获取元素的属性以进行比较.

It works fine but I don't think it will scale because a total of 185 jQuery calls are made, 184 of them which are getting the attribute of an element to do the comparison.

使用jQuery进行排序的更有效的方法是什么?

What is a more efficient way to do this sorting with jQuery?

推荐答案

如果您需要重复进行很多排序,那么朝着不涉及jQuery的更本地化的方法迈进是一件好事.否则,确实没有什么会带来明显的改变.

If you need to do lots of sorting repeatedly, it would be good to work towards a more native approach that doesn't involve jQuery. Otherwise, there really isn't much that is going to make a noticeable difference.

有些测试尝试了几种不同的方法-> http://jsperf .com/jquery-sort-by-numerical-property/2

Here are some tests trying a few different approaches -> http://jsperf.com/jquery-sort-by-numerical-property/2

这篇关于基于数值属性的DOM元素更有效的jQuery排序方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:48