2012-08-17 90 views
3

我有以下的HTML代碼:附加/添加到容器

<div class="container"> 
    <div><div>...</div><a class="child" href="#">Example</a></div>..</div></div> 
</div> 
<div class="container"> 
    <div><div>...</div><a class="child" href="#">Example</a></div>..</div></div> 
</div> 
. 
. 
. 
<div class="container"> 
    <div><div>...</div><a class="child" href="#">Example</a></div>..</div></div> 
</div> 

和我有以下的JavaScript腳本:

$('a.child').prependTo('div.container'); 

但這個代碼,而不是使每個a元素前置到他們自己的容器,使全部a元素前置於每個的容器。 我該如何解決這個問題?

謝謝!

回答

1

你可以嘗試each方法:

$('a.child').each(function(){ 
    $(this).prependTo($(this).closest('.container')); 
}) 

Fiddle

+1

謝謝大家對你的答案,他們都非常相似,併爲我工作。這一個似乎是'最乾淨的' – federicot 2012-08-17 20:18:09

3

對每個a.child進行迭代,並加上它。

$('a.child').each(function() 
{ 
    var $this = $(this); 
    $this.prependTo($this.closest('div.container')); 
}); 

http://jsfiddle.net/mattball/tRNUS

0

div.containera.child被作爲單獨的選擇。他們不相關。

你將不得不遍歷所有的a.child元素和選擇的父元素:

$('a.child').each(function() { 
    var $this = $(this); 

    $this.parents('div.container').prepend($this); 
});