在jQuery中交换包含动态内容的2个非常远的元素

时间:2016-01-08 20:15:01

标签: jquery

如果有这样的事情:

fooFunc

我知道你可以这样做:

for (i = 0; i < providers.length; i++) { var tNeeded = $("#select"+i).val(); var type = $("#select"+i).find('option:selected').text(); $("#select"+i).on("change", function() { tNeeded = $(this).val(); type = $(this).find('option:selected').text(); $("#target"+i).click({timeNeeded:tNeeded, timeType:reason, objectId:object[i].id}, fooFunc); }); $("#target"+i).click({timeNeeded:tNeeded, timeType:reason, objectId:object[i].id}, fooFunc); }

但是当你有这样的事情时,这种情况怎么样:

<div id="one">
  ...other elements inside...
</div>

<div id="two">
  ...other elements inside...
</div>

你要交换$("#two").before($("#one"));<div id="one"> ...other elements inside... </div> <div id="two"> ...other elements inside... </div> <div id="three"> ...other elements inside... </div> <div id="four"> ...other elements inside... </div> <div id="five"> ...other elements inside... </div> <div id="six"> ...other elements inside... </div> <div id="seven"> ...other elements inside... </div> <div id="eight"> ...other elements inside... </div> 你会如何在Jquery中做到这一点?每个div包含大量代码,并且此代码是动态更改的,因此只有主div的#eight#four等是稳定且可调用的。

1 个答案:

答案 0 :(得分:0)

感谢发现的bwegs。添加完整性。

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一样)。