[英]insertAfter, then remove previous element
Getting some weird behavior with a piece of code that's supposed to do simple DOM manipulation: 通过一段应该进行简单的DOM操作的代码来获得一些奇怪的行为:
b.detach();
b.insertAfter(a);
a.remove();
Initially the HTML looks like 最初,HTML看起来像
<a>
<b> </b>
</a>
(if it matters, I'm using b.wrap('<a></a>')
to build it) (如果重要,我正在使用b.wrap('<a></a>')
来构建它)
After that code runs it's supposed to move b
after a
: 代码运行后它应该移动b
后a
:
<a></a>
<b></b>
then remove a
: 然后取出a
:
<b></b>
but it doesn't. 但事实并非如此。 Instead a
remains there and b
just disappears. 相反, a
保留在那里, b
消失了。 Any ideas on what could be wrong? 有什么想法可能有问题吗?
I tried using after()
instead, reversing arguments, but getting the same result. 我尝试使用after()
代替,反转参数,但得到相同的结果。
remove b.detach() b.insertAfter(a); 删除b.detach()b.insertAfter(a); will move it 将移动它
I'm not sure what you mean, if I try it, it works the way you want it: 我不确定您的意思,如果尝试的话,它会以您想要的方式工作:
http://jsfiddle.net/8wy7v/ http://jsfiddle.net/8wy7v/
HTML: HTML:
<div id="test">
<a>
Test <b>Test</b>
</a>
</div>
<button id="change_dom">manipulate</button>
<br />
<textarea id="result"></textarea>
JS: JS:
$(document).ready(function(){
$('#change_dom').click(function(){
var a = $('a'),
b = $('b');
b.detach();
b.insertAfter(a);
a.remove();
$('#result').val($('#test').html());
});
});
Update: 更新:
This is how it can be done in the scenario described in this fiddle: http://jsfiddle.net/8wy7v/1/ 这是在此提琴中描述的场景中可以做到的方式: http : //jsfiddle.net/8wy7v/1/
var list = b.parents('ul')
b.insertAfter(list);
list.remove();
The reason is that wrap
does clone the elements - so what is referenced by a
never actually contains b
. 原因是wrap
确实会克隆元素-因此a
所引用的a
实际上不会包含b
。 Btw, the detach
is superfluous, as elements will be automatically removed when inserted elsewhere in the DOM. 顺便说一句, detach
是多余的,因为将元素插入DOM中的其他位置时,元素将被自动删除。
So to get the a
after which to insert, you will need to reselect it (eg by b.parent()
). 因此,要获取要插入的a
,您将需要重新选择它(例如,通过b.parent()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.