jQuery insertAfter到集合中(不在DOM中)

时间:2019-02-07 13:22:13

标签: jquery

在此示例中,我需要将elements容器中的元素#B添加到#source2变量中,但是在元素#A之后,并且不起作用。

但是,在下面的第二个示例中,如果我先将#B元素插入可以正常工作的source1容器中,但是我不需要将#B附加到source1容器中,希望避免每次将#B元素重新添加到#source2中(或克隆->附加->删除)

问题是: 如何将afterIn直接插入到不在DOM中的集合变量中?

//EXAMPLE 1
var elements = $('#source1').children();

var cloned = $('#B').clone(true,true);

cloned.insertAfter(elements.find('#A'));

console.log('example1',elements.length); //show #A and #C ... Expected #A,#B,#C

//EXAMPLE 2
//This work but I don't need to append #B into source1 container
$('#B').insertAfter($('#A'));

elements = $('#source1').children();
//here I need every time to re-append #B element into #source2 and I try to avoid that
$('#B').appendTo('#source2');

console.log('example2',elements.length); //show as expected #A,#B,#C
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="source1">
	<div id="A">
		A
	</div>
	<div id="C">
		C
	</div>
</div>
<div id="source2">
	<div id="B">
		B
	</div>
</div>

1 个答案:

答案 0 :(得分:0)

最后,我通过将整个容器source1克隆到elements变量中解决了该问题

我已经改变

var elements = $('#source1').children();

使用

var elements = $('#source1').clone();

    var elements = $('#source1').clone();

    var cloned = $('#B').clone();

    cloned.insertAfter(elements.find('#A'));

    //Now I can select all childrens  #A,#B,#C
    elements = elements.children();

    console.log(elements.length); // = 3 and show as Expected #A,#B,#C
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="source1">
	<div id="A">
		A
	</div>
	<div id="C">
		C
	</div>
</div>
<div id="source2">
	<div id="B">
		B
	</div>
</div>