排序DOM元素下令使用jQuery数组 [英] Sort DOM elements to order array with jQuery

查看:161
本文介绍了排序DOM元素下令使用jQuery数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚才我问这个问题:
<一href=\"http://stackoverflow.com/questions/13148941/javascript-sort-array-to-align-with-order-array/13148972\">javascript排序阵列基于什么被证明是虚假的premise与秩序阵列对齐。 (我已经过久,让我喘口气请)。

A moment ago I asked this question: javascript sort array to align with order array based on what turned out to be a false premise. (I've been up for too long, give me a break please).

我真正需要做的排序是DOM元素。 性能是关键在我的应用程序,因为这将非常CPU匮乏的情况下运行。因此,我已经是这样的:

What I really need to do is sort DOM elements. Performance is key in my application as it will be running in very CPU-poor situations. So what I have is something like this:

<div id="moduleWrap">
    <div class="module">Jack</div>    <!-- 0 -->
    <div class="module">Jill</div>    <!-- 1 -->
    <div class="module">Nancy</div>   <!-- 2 -->
    <div class="module">Tom</div>     <!-- 3 -->
    <div class="module">Cartman</div> <!-- 4 -->
</div>

和使用JavaScript:

And in JavaScript:

$modules = $('#moduleWrap .module');
order    = [3,1,4,0,2];

我需要的是这样的:

What I need is this:

<div id="moduleWrap">
    <div class="module">Tom</div>     <!-- 3 -->
    <div class="module">Jill</div>    <!-- 1 -->
    <div class="module">Cartman</div> <!-- 4 -->
    <div class="module">Jack</div>    <!-- 0 -->
    <div class="module">Nancy</div>   <!-- 2 -->
</div>

我认为(错误的),我可以排序的jQuery对象,只是追加的结果。事实并非如此。

I thought (wrongly) that I could sort the jQuery object and simply append the result. This is not so.

推荐答案

我只想遍历订单阵列,并相应地重新排列DOM元素:

I would just iterate over the order array and rearrange the DOM elements accordingly:

var elements = [];
$.each(order, function(i, position) {
    elements.push($modules.get(position));
});

$('#moduleWrap').append(elements);

DEMO

要提高性能,可以越来越多的jQuery带走。例如:

To increase performance, you can take away more and more jQuery. For example:

var wrapper = document.getElementById('moduleWrap');
for(var i = 0, l = order.length; i < l; i++) {
    wrapper.appendChild($modules.get(order[i]));
}

DEMO

jQuery是伟大的,因为它使事情变得简单,但如果你需要高性能,你应该去,而没有它。

jQuery is great because it makes things easy, but if you need high performance, you should rather go without it.

这篇关于排序DOM元素下令使用jQuery数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆