用jQuery重新排序div [英] Re-ordering divs with jQuery

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

问题描述

是否可以使用jQuery重新排序一些div。我有几个div,我想根据div中的数据索引号在页面加载时重新排序。

Is it possible to re-order some divs with jQuery. I have few divs and I would like re-order them on page load according data-index number that is in divs.

现在:

<div class="score" data-index="3">3</div>
<div class="score" data-index="2">2</div>
<div class="score" data-index="1">1</div>
<div class="score" data-index="4">4</div>

我想要的是什么:

<div class="score" data-index="1">1</div>
<div class="score" data-index="2">2</div>
<div class="score" data-index="3">3</div>
<div class="score" data-index="4">4</div>

我相信这应该可以用jQuery实现。我去每个div并得到数据索引号,但我该如何做实际订购:D

I believe this should be possible with jQuery. I go each div and get the data-index number but how do I do the actual ordering :D

Thx!

编辑:有一件事是HTML中的顺序可能会因每页加载而异(订单可以是3,2,1,4或4,1,3,2或其他任何内容)。

one thing is that the order in HTML can vary on each page load (the order can 3,2,1,4 or 4,1,3,2 or anything).

这是我现在唯一的JS:

And this is the only JS I have now:

$("html .score").each(function(index, domEle) {
            var score = $(domEle).attr("data-index");
            alert(score);
        });

只需获取数据索引号就可以提醒它。

Just gets data-index number alerts it.

推荐答案

HTML

<div class="sortable">
    <div class="score" data-index="3">3</div>
    <div class="score" data-index="2">2</div>
    <div class="score" data-index="1">1</div>
    <div class="score" data-index="4">4</div>
</div>

jQuery
---------升序

jQuery ---------ascending

$('.sortable').each(function(){
    var $this = $(this);
    $this.append($this.find('.score').get().sort(function(a, b) {
        return $(a).data('index') - $(b).data('index');
    }));
});

---------降序

---------descending

$('.sortable').each(function(){
    var $this = $(this);
    $this.append($this.find('.score').get().sort(function(a, b) {
        return $(b).data('index') - $(a).data('index');
    }));
});

现场演示

这篇关于用jQuery重新排序div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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