需要一些jQuery帮助将一个DIV复制到另一个DIV中,希望这是可能的。我有以下HTML:
<div class="container">
<div class="button"></div>
</div>
然后我在页面的另一个位置有另一个DIV,我想将“button”DIV复制到下面的“package”DIV中:
<div class="package">
Place 'button' div in here
</div>
需要一些jQuery帮助将一个DIV复制到另一个DIV中,希望这是可能的。我有以下HTML:
<div class="container">
<div class="button"></div>
</div>
然后我在页面的另一个位置有另一个DIV,我想将“button”DIV复制到下面的“package”DIV中:
<div class="package">
Place 'button' div in here
</div>
您需要使用clone()
方法来获取元素的深拷贝:
$(function(){
var $button = $('.button').clone();
$('.package').html($button);
});
完整演示:http://jsfiddle.net/3rXjx/
来自jQuery文档:
.clone()方法执行所匹配元素集的深度复制,意味着它会复制匹配的元素以及它们所有的后代元素和文本节点。当与其中一种插入方法结合使用时,.clone()是在页面上复制元素的便捷方式。
使用 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>
$(".package").html($(".button").html())
$(function(){
$('.package').click(function(){
var content = $('.container').html();
$(this).html(content);
});
});
$(document).ready(function(){
$("#btn_clone").click(function(){
$("#a_clone").clone().appendTo("#b_clone");
});
});
.container{
padding: 15px;
border: 12px solid #23384E;
background: #28BAA2;
margin-top: 10px;
}
<!DOCTYPE html>
<html>
<head>
<title>jQuery Clone Method</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="container">
<p id="a_clone"><b> This is simple example of clone method.</b></p>
<p id="b_clone"><b>Note:</b>Click The Below button Click Me</p>
<button id="btn_clone">Click Me!</button>
</div>
</body>
</html>
$
,例如var $button
?我相信在 JavaScript 中可以直接声明为var button
。 - KNU