Re-ordering divs with jQuery

谁都会走 提交于 2019-12-08 09:03:43

问题


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.

Now:

<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>

What I want:

<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>

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!

EDIT: 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).

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.


回答1:


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 ---------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');
    }));
});

Live demo




回答2:


function sortDivs(a,b){  
    return $(a).data("index") > $(b).data("index") ? 1 : -1;  
};  


$(".score").sort(sortDivs).appendTo($("#results"));

Here's a demo



来源:https://stackoverflow.com/questions/7137804/re-ordering-divs-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!