jQuery clone()用于创建匹配元素的副本。 它还支持一个布尔参数,以指示是否需要复制事件处理程序和数据以及匹配的元素。
1.克隆html元素
例如,您将克隆以下html代码。
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
使用clone()创建上述元素的副本,并将复制的元素放在包含“ smallBox”类名称的div标记之后。
$('.smallBox').clone().insertAfter(".smallBox");
结果 :
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
2.克隆事件处理程序
下一个示例将克隆按钮单击事件,您将复制包含id为“ cloneButton1”的按钮。
<button id="cloneButton1">clone()</button>
<script type="text/javascript">
$("#cloneButton1").click(function () {
$('.smallBox').clone().insertAfter(".smallBox");
});
</script>
如果使用默认的clone()或clone(false)方法,它将仅复制按钮元素,而不复制click()事件处理程序。
$('#cloneButton1').clone().insertAfter("#cloneButton1");
若要复制click()事件处理程序以及匹配的元素,应使用clone(true)。
$('#cloneButton1').clone(true).insertAfter("#cloneButton1");
自己尝试
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
.smallBox{
padding:8px;
border:1px solid blue;
margin:8px;
}
.smallInnerBox{
padding:8px;
border:1px solid green;
margin:8px;
}
</style>
</head>
<body>
<h1>jQuery clone() example</h1>
<div class="smallBox">
I'm a small box
<div class="smallInnerBox">I'm a small small inner box</div>
</div>
<p>
<button id="cloneButton1">clone()</button>
<button id="cloneButton2">clone() button (default)</button>
<button id="cloneButton3">clone(true) button</button>
<button id="reset">reset</button>
</p>
<script type="text/javascript">
$("#reset").click(function () {
location.reload();
});
$("#cloneButton1").click(function () {
$('.smallBox').clone().insertAfter(".smallBox");
});
$("#cloneButton2").click(function () {
$('#cloneButton1').clone(false).insertAfter("#cloneButton1");
});
$("#cloneButton3").click(function () {
$('#cloneButton1').clone(true).insertAfter("#cloneButton1");
});
</script>
</body>
</html>