开发者

Loop through jQuery elements and sort them as illustrated

开发者 https://www.devze.com 2023-01-28 12:47 出处:网络
I have an unknown number of HTML elements which I have to sort for a type of carousel. Imagine it is a list of div\'s like the following:

I have an unknown number of HTML elements which I have to sort for a type of carousel.

Imagine it is a list of div's like the following:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<!-- etc -->

Let's say that开发者_StackOverflow社区, for instance, i have 13 div's i need to sort. The following has to been done:

Loop through jQuery elements and sort them as illustrated

Don't get too distracted by the highlighted 8, that's just the active items I'm showing.

I can't quite figure it out, maybe I've been staring at the thing for too long or tried too many alternatives.

edit: the illustration is maybe a bit distracting.

the result I want is:

<div>1</div>
<div>3</div>
<div>5</div>
<div>7</div>
<div>9</div>
<div>11</div>
<div>13</div>
<div>2</div>
<div>4</div>
<div>6</div>
<div>8</div>
<div>10</div>
<div>12</div>


If they were in a container, say <div id="container">, just takes the :odd ones and append them at the end using .appendTo(), like this:

$("#container div:odd").appendTo("#container");

You can try it out here. If they're in something else, the concept it the same, take the odd ones, append them to the parent at the end.


Imagine you have two rows #row1 and #row2. Then you can traversing through original collection (which in #collection block) this way:

var $row1 = $('#row1');
var $row2 = $('#row2');
$('#collection div').each(function(i) {
    if (i % 2) {
        $(this).appendTo($row2)
    } else {
        $(this).appendTo($row1)
    }
});


$(function() {
   $wrapper = $("#wrapper"); 
   $("div:odd", $wrapper).appendTo($wrapper);
});

Example: http://jsfiddle.net/Ed2We/


How about using 2 for loops?

for(var i=0, j=yourList.length/2; i<j; i+=2){
    doSomething(yourList[i]);
}
for(var i=1, j=yourList.length/2; i<j; i+=2){
    doSomething(yourList[i]);
}


var r1 = new Array();
var r2 = new Array();
$("DIV","#in").each(function(){
    if(parseInt($(this).text()) % 2 == 1 )
        r1.push($(this));
    else
        r2.push($(this));
});
$.fn.append.apply( $("#in"), $.merge(r1,r2));

output is:

<div>1</div>
<div>3</div>
<div>5</div>
<div>7</div>
<div>9</div>
<div>11</div>
<div>13</div>
<div>2</div>
<div>4</div>
<div>6</div>
<div>8</div>
<div>10</div>
<div>12</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消