在循环中将内容从div1移动到div2

时间:2016-06-13 22:25:39

标签: jquery foreach append

我搜索了一个解决方案,但是找不到它,因为循环正在生成但是我没有得到我想要的结果。

以下是这种情况:带有child-1和child-2的父div处于循环中。我需要在循环中将内容从child-2移动到child-1。

提前感谢您的帮助:)

$('.parent').each(function(){
  $('.link').appendTo('.child-1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div class='parent'>
	<p class="child-1">	Move link one here	</p>
	<p class="child-2">		
		<a class="link" href="#ID-1"> link one </a>	
	</p>
</div>


<div class='parent'>
	<p class="child-1">	Move link two here	</p>
	<p class="child-2">		
		<a class="link" href="#ID-2"> link two </a>
	</p>
</div>


<div class='parent'>
	<p class="child-1">	Move link three here	</p>
	<p class="child-2">		
		<a class="link" href="#ID-3"> link three</a>	
	</p>
</div>

2 个答案:

答案 0 :(得分:1)

你需要在你的孩子2 div中创建一个循环,试试这段代码:

&#13;
&#13;
//loop in child-2 div
$('.child-2').each(function(i, item) {
  //get the parent element and find the child-1, the child-1 append the html of child-2
  $(this).parent().find('.child-1').html($(this).html());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div class='parent'>
	<p class="child-1">	Move link one here	</p>
	<p class="child-2">		
		<a class="link" href="#ID-1"> link one </a>	
	</p>
</div>


<div class='parent'>
	<p class="child-1">	Move link two here	</p>
	<p class="child-2">		
		<a class="link" href="#ID-2"> link two </a>
	</p>
</div>


<div class='parent'>
	<p class="child-1">	Move link three here	</p>
	<p class="child-2">		
		<a class="link" href="#ID-3"> link three</a>	
	</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

此代码将具有类“link”的所有元素附加到具有类“.child-1”的所有子级:

$('.link').appendTo('.child-1');

你应该做的是使用jQuery的find()方法将元素限制为每个父元素的后代:

$('.parent').each(function() {
  $(this).find('.link').appendTo($(this).find('.child-1'));
});

$('.parent').each(function() {
  $(this).find('.link').appendTo($(this).find('.child-1'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
  <p class="child-1">Move link one here</p>
  <p class="child-2">
    <a class="link" href="#ID-1"> link one </a>	
  </p>
</div>

<div class='parent'>
  <p class="child-1">Move link two here</p>
  <p class="child-2">
    <a class="link" href="#ID-2"> link two </a>
  </p>
</div>

<div class='parent'>
  <p class="child-1">Move link three here</p>
  <p class="child-2">
    <a class="link" href="#ID-3"> link three</a>	
  </p>
</div>