jquery:在DOM中切换元素
使用jquery在DOM中切换两个元素的最佳方法是什么?
some other elements in here.... some other elements in here....
应该结束:
some other elements in here.... some other elements in here....
你会让人们告诉你在before
, after
和after
使用jQuery,但要小心,如果在任一元素的任何一侧有文本节点,那么这可能会搞砸了(更多内容如下)。
因此(对于不使用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, 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]); }); });
first text node this is switchme1 with some other elements in heretest second text node this is switchme2 with some other elements in here this is switchme3 with some other elements in here this is switchme4 with some other elements in here this is switchme5 with some other elements in here third text node
看到这个堆栈溢出问题。
基本上说:
jQuery("#element1").before(jQuery("#element2"));
要么
jQuery("#element1").after(jQuery("#element2"));
美丽呃? – 归功于乐天。