用
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>
应该结束于:
<div id="switchme1">some other elements in here....</div> <div class="some other elements"></div> <div id="switchme2">some other elements in here....</div>
解决方法
你会让人们告诉你使用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); }
注意,如果参考元素(next1或next2上面)为null,那么很好insertBefore
正确处理(通过在父级结尾添加,如appendChild).
用法结合jQuery:
swapElements($("#switchme1")[0],$("#switchme2")[0]);
实例:
jQuery(function($) { function swapElements(elm1,elm2,elm3,elm4,elm5) { var parent1,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]); }); });
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>
更多关于jQuery的before
,after
等:因为jQuery往往给你访问主要是元素(这是你想要95%的时间!),如果要交换的元素周围有文本节点,使用这些方法会混乱的事情. (你也必须记住哪一个在前面,或者想出来.)相比之下,上面的swapElements方法无论元素是被其他元素还是文本节点包围,你不必记住弄清楚哪个应该在前面.