使用jquery在DOM中切换两个元素的最佳方法是什么?
<div id="switchme2">some other elements in here....</div>
<div class="some other elements"></div>
<div id="switchme1">some other elements in here....</div>
Run Code Online (Sandbox Code Playgroud)
应该结束:
<div id="switchme1">some other elements in here....</div>
<div class="some other elements"></div>
<div id="switchme2">some other elements in here....</div>
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 33
你会得到别人告诉你使用jQuery的before,after和这样的,但要注意,这可以胡来的事情,如果那里是文本节点上的任一元素的两边(更多的下面).
因此(对于不使用jQuery的人),您可以直接使用DOM:
function swapElements(elm1, elm2) {
var parent1, next1,
parent2, next2;
parent1 = elm1.parentNode;
next1 = elm1.nextSibling;
parent2 = elm2.parentNode;
next2 = elm2.nextSibling;
parent1.insertBefore(elm2, next1);
parent2.insertBefore(elm1, next2);
}
Run Code Online (Sandbox Code Playgroud)
注意,如果参考元素(next1或next2上面)是null; insertBefore正确处理(通过在父级的末尾添加,就像appendChild那样).
用法结合jQuery:
swapElements($("#switchme1")[0], $("#switchme2")[0]);
Run Code Online (Sandbox Code Playgroud)
实例:
jQuery(function($) {
function swapElements(elm1, elm2, elm3, elm4, elm5) {
var parent1, next1,
parent2, next2,
parent3, next3,
parent4, next4,
parent5, next5;
parent1 = elm1.parentNode;
next1 = elm1.nextSibling;
parent2 = elm2.parentNode;
next2 = elm2.nextSibling;
parent3 = elm3.parentNode;
next3 = elm3.nextSibling;
parent4 = elm4.parentNode;
next4 = elm4.nextSibling;
parent5 = elm5.parentNode;
next5 = elm5.nextSibling;
parent1.insertBefore(elm2, next1);
parent2.insertBefore(elm3, next2);
parent3.insertBefore(elm4, next3);
parent4.insertBefore(elm5, next4);
parent5.insertBefore(elm1, next5);
}
$("#btnSwitch").click(function() {
swapElements($("#switchme1")[0], $("#switchme2")[0], $("#switchme3")[0], $("#switchme4")[0], $("#switchme5")[0]);
});
});Run Code Online (Sandbox Code Playgroud)
first text node
<div id="switchme1">this is <strong>switchme1</strong> with <strong>some other elements</strong> <em>in here<div>test</div></em></div>
second text node
<div id="switchme2">this is <strong>switchme2</strong> with <strong>some other elements</strong> <em>in here</em></div>
<div id="switchme3">this is <strong>switchme3</strong> with <strong>some other elements</strong> <em>in here</em></div>
<div id="switchme4">this is <strong>switchme4</strong> with <strong>some other elements</strong> <em>in here</em></div>
<div id="switchme5">this is <strong>switchme5</strong> with <strong>some other elements</strong> <em>in here</em></div>
third text node
<input type="button" id="btnSwitch" value="Switch Em!">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
更多关于jQuery的before,after和这样的:因为jQuery倾向于给你访问主要是为了元素(!这是你想要什么样的95%的时间),如果你想要交换有他们周围文本节点的元素,使用这些方法会乱事情.(你还必须记住哪一个在前面或者弄明白.)相反,swapElements无论元素是否被其他元素或文本节点包围,上面的方法都可以工作,而且你不必记住或计算哪个应该在前面.