PrependTo项仅在Jquery中的ONCE

我有以下DOM树关系

我想要做的是在.table-class移动.div-class ,但是当我使用prependTo('.div-class')运行jQuery时,我得到以下输出:

 

我只需要在.table-class移动.table-class的第一个/立即出现。 有什么指针吗?

问题是因为您将所有 .div-class元素.div-class添加到所有.table-class元素中。

要解决这个问题,你可以在.div-class元素上使用prepend() ,向方法传递一个返回元素前置的函数。 试试这个:

 $('.div-class').prepend(function() { return $(this).next('table'); }); 
 div { padding: 10px; margin: 0 0 10px; border: 1px solid #C00; } table { height: 20px; border: 1px solid #0C0; width: 100%; } 
  

截至目前,您正在将表格添加到所有.div-class元素中。 你可以迭代相对前置元素。

 $('.table-class').each(function() { $(this).prependTo($(this).prev('.div-class')); }); 
  
First Div
1
Second Div
2

尝试next()

 $('.div-class').each(function(){ $(this).prepend(function() { return $(this).next('.table-class') }) }) console.log($('body')[0].outerHTML)