2016-03-08 120 views
0

如果我克隆一個元素,那麼如果我想自定義該元素(由id)如何定製克隆的元素?如果我克隆一個元素,當我定製(CSS)該元素如何可以定製克隆的元素?

我的嘗試:

<div id="A"> //the element that will be clone 
</div> 

<div id="box" style="margin-top: 50px"> //into this box 
</div> 

CSS

#A{ 
    width: 100px; 
    height: 100px; 
    background: #000; 
} 

JS

$('#A').clone(true).appendTo('#box'); 
$('#A').css('background','#ff0000'); 

//i want to get red background also to element cloned, infact only the true original element change color :/ 

這是的jsfiddle:https://jsfiddle.net/t90ptkcz/1/

我希望這是可能的,你可以幫助米即非常感謝和抱歉,我的英語水平:)

+2

更改訂單。首先申請CSS然後做克隆。 –

+0

您將需要更改克隆元素的'id'屬性,因爲在文檔中id必須是唯一的。如果您想將元素分組在一起,請使用一個類。 –

回答

3

ID # selector發現從DOM獨特的單個元素雖然有ID存在相同的DOM但class . selector多個元素用於獲取元素的組,具有相同的類名

<div id="A" class="someClass" > //the element that will be clone 
</div> 

<div id="box" style="margin-top: 50px"> //into this box 
</div> 

JS

$('#A').clone(true).appendTo('#box'); 
$('.someClass').css('background','#ff0000'); 
0

我更喜歡從@shu的答案,但是我不知道在這種情況下,這可能是有用的,可以通過實現一個jQuery插件有兩種方法正是你想要的實現:

  • $.fn.cloneAndRemember - 將克隆的元素,並在源元件和其克隆(或克隆)存儲到字典
  • $.fn.withClones - 會給你jQuery對象集合,其包括所選擇的元素及其所有克隆(從字典檢索)

使用情況下會再看看這樣的:你的jQuery線

$('#A').cloneAndRemember(true).appendTo('#box'); 
$('#A').withClones().css('background','#ff0000');