0

关于 jquery 克隆元素的快速问题。很长一段时间,我认为我必须在插入它(到 DOM 树)后重新 jqueryfy 克隆元素,但下面的代码工作正常。

HTML

<div id="test">test<"/div>
<button id="btn">push</div>

JavaScript

var $clone = $('#test').clone(),
    $btn = $('#btn');

$clone.prop('id','clone').appendTo('body');

// I thought this is necessary but it's not.
// var $clone = $('#clone');
$btn.on('click',function(){
  $clone.toggleClass('someclass');
});

那么有人可以告诉我为什么吗?

4

1 回答 1

0

实际上,如果您将看到jQuery.clone()方法的文档,该方法会创建匹配元素集的深层副本。

因此,当您克隆元素时,该clone方法会返回元素的副本。即使您再次将其附加到正文中,复制元素的引用仍保留在变量中。所以你不需要再次得到它来操纵它。

你能明白:

var $clone = $('#test').clone();
// you created the copy of the $('#test') element and held it in $clone variable
$clone.attr('id','clone').appendTo('body'); // you should prefer prop() instead
// you changed it's id but it is still held in $clone
$clone.toggleClass('someclass');
// and you can toggle it's class as it is still held in $clone variable
于 2019-05-20T12:14:35.857 回答