[英]Transfer grandchildren to become children
I have elements all of the .dataCard
class divided into a left and right column, which are children of the main container. 我将.dataCard
类的所有元素分为左右两列,它们是主容器的子级。 So the .dataCard
elements are grandchildren of #main
. 因此.dataCard
元素是.dataCard
的孙#main
。
I'm trying to go from the left column to the right column and take the first child from each column and transfer it into #main
then remove it from the column it came from; 我试图从左边的列转到右边的列,并从每个列中取出第一个孩子,并将其转移到#main
然后将其从其来源的列中删除; thus, making it a child of #main
and not a grandchild. 因此,使其成为#main
的孩子而不是孙子。
Here is what I have tried, but when I run it, I get an empty `#main': 这是我尝试过的方法,但是当我运行它时,我得到一个空的#main:
$('.dataCard').each(function(){
$('#main').append($('#left').first());
$('#left').first().remove();
$('#main').append($('#right').first());
$('#right').first().remove();
});
I've also tried this, but I understand why this also causes an empty #main
because it clears the #main
when it writes the html of #main
because then there is nothing to reference as now the #left
and #right
are gone. 我也尝试过此方法,但是我理解为什么它也会导致空的#main
因为它在写入#main
的html时会清除#main
,因为此时#left
和#right
都消失了,因此没有什么可引用的。
$('.dataCard').each(function(){
$('#main').html($('#left').first());
$('#left').first().remove();
$('#main').html($('#right').first());
$('#right').first().remove();
});
How can I transfer the .dataCard
elements in the order, one from the left column, one from the right column, into #main
? 如何将.dataCard
元素按顺序(从左列到右列) #main
到#main
?
Edit: 编辑:
My markup: 我的标记:
<div id="main">
<div id="left">
<div class="dataCard" data-cardNumber="1">...</div>
<div class="dataCard" data-cardNumber="3">...</div>
<div class="dataCard" data-cardNumber="5">...</div>
</div>
<div id="right">
<div class="dataCard" data-cardNumber="2">...</div>
<div class="dataCard" data-cardNumber="4">...</div>
</div>
var x = $('#main .dataCard').sort(function (a, b) {
return $(a).data('cardnumber') - $(b).data('cardnumber');//sort according to data-cardNumber attribute
}).appendTo('#main', function () { //append to div with id main
$('#left,#right').remove();//remove div with id left and right
});
$('#main').append($('#left').find('.dataCard').first()); $('#main').append($('#right').find('.dataCard').first());
or .prepend() 或.prepend()
$('#main').prepend($('#left').find('.dataCard').first()); $('#main').prepend($('#right').find('.dataCard').first());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.