HTML 示例:
<h2 class="x1">1</h2>
<h2 class="x2">2</h2>
<h2 class="x3">3</h2>
<h2 class="x4">4</h2>
<h2 class="x5">5</h2>
我想切换...
1
2 <---
3 |
4 |
5 <---
所以我很喜欢这个
$('.x2').insertBefore('.x5');
$('.x5').insertBefore('.x2');
所以我得到这样的结果
1
3
4
5 <---
2 <---
我怎样才能得到像...这样的结果?
1
5 <---
3 |
4 |
2 <---
Playground : http://jsfiddle.net/l2aelba/aHwSJ/
PS:如果可能我不想这样做喜欢
$('.x2').insertBefore('.x5');
$('.x5').insertBefore('.x3');
我只需要选择元素 2 个元素(而不是其他元素)
最佳答案
您想要在 .x2
的下一个同级之前插入 .x5
,而不是在 .x2
本身之前。
var next = $('.x2').next();
$('.x2').insertBefore('.x5');
$('.x5').insertBefore(next);
只有当 .x2
不是最后一个同级时,这才有效。
关于javascript - .insertBefore() 在 2 个 div 之间切换位置 (HTML),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913988/