开发者

Reorder DOM elements order when using jQuery each()

Is there any way to modify the 开发者_JAVA技巧order JQuery each() accesses the elements on the page?

I.e I have 4 elements on the page and I want element 3 to come first, then 2, then 4 and then 1.

Thanks

Richard


Assume you reorder images.

imgs = $( 'img' );

imgs.eq( 3 ).insertBefore( imgs.eq( 1 ) );

imgs.eq( 1 ).insertAfter( imgs.eq( 4 ) );

Should do the trick.


.each() will deliver the nodes the same way they appear in the DOM. But it also passes the index into the callback functions. So if you need to act differently, check the index

$('object').each(function(index) {
    if( index === 2)
        alert('yay');
});

Ref.: .each()


if you know that why not just reference them in that order without using each.


$items = $('.my-selector');
my_array = [ $items.get(2), $items.get(1), $items.get(3), $items.get(0) ];
jQuery.each(my_array, callback_function);

Note that the jQuery object is 0-indexed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜