简体   繁体   English

动态地将内容从一个div追加/添加到另一个div-使用JS / jQuery

[英]Dynamically append/prepend content from one div to another - with JS/jQuery

I have a 3 column div with multiple rows. 我有一个三列的div多行。 What is the most dynamic way to extract content from the first div and append/prepend this to the 3rd div - Ensuring that all following divs follow along. 从第一个div提取内容并将其追加/添加到第三个div的最动态方式是什么-确保随后的所有div都遵循。

here is my example code: 这是我的示例代码:

  <div class="content"> <div class="item"> <div class="col1"> <div class="img1"> <img src="img_in_first_col"> </div> </div> <div class="col2"></div> <div class="col3"> <div class="img2"> <img src="img_in_third_col"> </div> </div> </div> <div class="item"> <div class="col1"> <div class="img1"> <img src="img_in_first_col"> </div> </div> <div class="col2"></div> <div class="col3"> <div class="img2"> <img src="img_in_third_col"> </div> </div> </div> <div class="item"> <div class="col1"> <div class="img1"> <img src="img_in_first_col"> </div> </div> <div class="col2"></div> <div class="col3"> <div class="img2"> <img src="img_in_third_col"> </div> </div> </div> </div> 

I've tried using something along the lines of: 我试着使用一些类似的东西:

 $('.item .col1 .img1').each(function(){ $(this).prependTo('.item .col3 .img2') }) 
but what i get is all the images being added to all the rows. 但是我得到的是将所有图像添加到所有行。 Please help! 请帮忙! thanks in advance 提前致谢

Should be as simple as this: 应该像这样简单:

$(".col1").each(function (index, element) {
  $(this).closest(".col3").prepend($(this).contents());
});

You could use this to insert column 1 after column 3: 您可以使用它在第3列之后插入第1列:

$('.col1').each(function(){
  $(this).insertAfter($(this).siblings('.col3'));
});

... or before column 3: ...或在第3列之前

$('.col1').each(function(){
  $(this).insertBefore($(this).siblings('.col3'));
});

Used jQuery functions: 使用的jQuery函数:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM