2013-05-08 64 views
-1

這甚至可能嗎?使用數據屬性克隆並附加一個Div給Div使用

我的主div裏面有一個div,我克隆了它併爲每個克隆的元素分配了一個唯一的數據屬性。這些克隆的div裏面有div,我也希望它們也被克隆。那麼,我將如何使用.clone().appendTo()方法來做到這一點?

這裏是我的代碼的某些部分:

<div id="card_grid"> 
    <div class="cards_slot" data-unique="0" id="cards_slot"> 
     <div class="play_cards"></div> 
    </div> 
</div> 

的jQuery,JavaScript的:

//Clone the card slots 
for(var i=0;i<=18;i++) { 
    $(".cards_slot:first-child").clone().appendTo("#card_grid"); 
} 

//Initialize the cards slots' position 
$("#card_grid").children().each(function(index) { 
    $(this).css({ 
     "left" : ($(this).width() + 50) * (index % 5), 
     "top" : ($(this).height() + 20) * Math.floor(index/5) 
    }); 
    var child_position = ($(this).parent().children().index(this)); 
    var element_id = $(this).attr('id'); 
    var new_id = element_id + child_position; 
    $(this).attr('id', new_id); 

    $(this).attr('data-unique', child_position); 
}); 
+0

當克隆它的孩子們太克隆的元素。檢查DOM,你會看到克隆的_empty_ div後代。 – undefined 2013-05-08 00:45:08

+0

@undefined,是的。我真正想做的是克隆我克隆的div內的div。 – JetPro 2013-05-08 00:47:07

+0

和什麼意思?選擇器? – Johnny000 2013-05-08 00:48:40

回答

1

是的,這是可能的。

var $toBeCloned = $(".cards_slot:first-child"); 

for(var i=0;i<=18;i++) { 
    var $cloned = $toBeCloned.clone(); 
    $cloned.find('div:first').clone().appendTo($cloned); 
    $cloned.appendTo("#card_grid"); 
} 

http://jsfiddle.net/3JSPc/