0

我有这样的元素:

<div class="item pix-txt medium">
   <span class="animated jumbo bold" data-sequence="5" data-entrance="fade" data-exit="fade" data-top="50" data-left="-150">Masters of the Internet</span> 
   <span class="animated medium" data-sequence="3" data-entrance="fade" data-exit="fade">
   <span class="animated medium" data-sequence="2" data-entrance="fade" data-exit="fade"></span>

</div>

每个.animated跨度都有一个data-sequence附加的整数。按值对javascript数组中的这些元素进行排序的最佳方法是什么data-sequence

4

2 回答 2

1

如果你想在 JavaScript 数组中对它们进行排序,而不是对 DOM 进行排序,你可以这样做;

var ar = $('.item').children().get().sort(function (a, b) {
    return $(a).data('sequence') - $(b).data('sequence');
});

这使用 将 jQuery 对象转换为 Array get(),然后使用Array sort()函数

注意ar将是一个 JavaScript 数组,而不是一个 jQuery 对象。

于 2013-04-27T11:13:37.977 回答
1

这是一个纯 JS 解决方案。您可能需要根据需要调整选择器部分。

function sortElementsByAttribute(selector, attribute) {
    // Fetch all elements matching the selector, and convert it to an Array from a NodeList
    var elements = [].slice.call(document.querySelectorAll(selector));

    // `sort` sorts inplace
    elements.sort(function (n1, n2) {
        // convert `attribute` attribute to integers, and sort the elements by that.
        return parseInt(n1.getAttribute(attribute), 10) - parseInt(n2.getAttribute(attribute), 10);
    });

    // Loop through the sorted elements
    for (var i = 0; i < elements.length; i++) {
        var node = elements[i];
        // This would move the `node` to be the last child of its parent node,
        // basically sorting the elements
        node.parentNode.appendChild(node);
    }
}

sortElementsByAttribute(".item span", "data-sequence");

http://jsfiddle.net/QssyK/

于 2013-04-27T11:39:05.310 回答