【问题标题】:Clone and Append a Div to a Div using Data Attribute使用数据属性克隆 Div 并将其附加到 Div
【发布时间】:2013-05-08 00:37:42
【问题描述】:

这可能吗?

我的主 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);
});

【问题讨论】:

  • 当你克隆一个元素时,它的子元素也会被克隆。检查 DOM,您将看到克隆的 empty div 后代。
  • @undefined,是的。我真正想做的是在我克隆的 div 中克隆 div。
  • 还有什么意义?选择器?
  • 我的代码结构错误。我应该先克隆内部 div(子级),然后克隆外部 div(父级)。

标签: jquery clone


【解决方案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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 2014-05-22
    • 2019-04-29
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    相关资源
    最近更新 更多