在dom中重新排序html元素 [英] Reorder html elements in dom

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

问题描述

我有一个元素列表:

<div class="wrapper">
    <div class="abc"></div>
    <div class="abc"></div>
    <div class="abc"></div>
</div>

我有一个或多个数字代表新订单:

And I have an array or numbers which represent new order:

var arr = [2,1,0];

我想将这些abc div重新定位到父包装内的新位置。

I would like to reposition these abc divs to new positions inside parent wrapper.

重要的是,abc divs附加了事件和数据,这需要保留!

Important thing is that abc divs have events and data attached to them and this needs to be preserved!

我想出了这个它似乎按预期工作:

I have came up with this and it seems to be working as expected:

var wrapper = $('.wrapper'), items = wrapper.children('div.abc');

var orderedItems = $.map(arr, function(value) {
    return $(items).clone(true,true).get(value);
});
wrapper.empty().html(orderedItems);

我想确保这是正确的方法。

I wanted to make sure this is the right way.

如果可能,我也可以使用javascript解决方案。

I could do with javascript solution as well if possible.

推荐答案

无需复制所有项目..两次

no need to copy all items .. twice

var wrapper = $('.wrapper'), 
    items = wrapper.children('.abc'),
    arr = [2,1,0];

//items.detach(); if arr doesn't reuse all items
wrapper.append( $.map(arr, function(v){ return items[v] }) );

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

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