jQuery将DIV复制到另一个DIV中

Dan*_*Dan 93 html javascript jquery

需要一些jquery帮助将DIV复制到另一个DIV并希望这是可能的.我有以下HTML:

  <div class="container">
  <div class="button"></div>
  </div>
Run Code Online (Sandbox Code Playgroud)

然后我在我的页面中的另一个位置有另一个DIV,我想将'button'div复制到以下'package'div:

<div class="package">

Place 'button' div in here

</div>
Run Code Online (Sandbox Code Playgroud)

chr*_*hrx 150

您将需要使用该clone()方法以获取元素的深层副本:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});
Run Code Online (Sandbox Code Playgroud)

完整演示:http://jsfiddle.net/3rXjx/

来自jQuery文档:

.clone()方法执行匹配元素集的深层副本,这意味着它复制匹配的元素以及它们的所有后代元素和文本节点.与其中一种插入方法结合使用时,.clone()是在页面上复制元素的便捷方式.

  • @KNU这不是必需的,但它是jQuery世界中的常见约定.它表明$ button变量是一个jQuery对象.请参阅http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign (19认同)
  • 你能告诉我为什么我们在`var $ button`中需要`$`.我相信js你可以简单地将var声明为`var button`. (5认同)

Sun*_*S.M 20

使用clone和appendTo函数复制代码:

这里也是jsfiddle的工作示例

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
    $(function(){
        $('#copy').clone().appendTo('#copied');
    });
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)