gpt4 book ai didi

jquery:切换 DOM 中的元素

转载 作者:行者123 更新时间:2023-12-03 22:11:59 26 4
gpt4 key购买 nike

使用 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);
}

请注意,如果引用元素(上面的 next1next2)为 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
<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 方法无论元素是否被其他元素或文本节点包围都有效,并且您不必记住或弄清楚哪个应该放在前面。

关于jquery:切换 DOM 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com