Jqueryclone()实例
Jquery clone() 函数被用来创建匹配元素的一份拷贝。其也支持比尔参数用来指示是否拷贝匹配元素的数据和事件处理器。
1 拷贝html 元素
例如: 我们将拷贝以下的html 代码
<divclass="smallBox">
I'm a small box
<divclass="smallInnerBox">I'm a small small inner box</div>
</div>
使用clone() 来创建以上元素的一份拷贝,并把拷贝元素放在包含一个类名为”smallBox”的div 标签后。
$('.smallBox').clone().insertAfter(".smallBox");
结果如下:
<divclass="smallBox">
I'm a small box
<divclass="smallInnerBox">I'm a small small inner box</div>
</div>
<divclass="smallBox">
I'm a small box
<divclass="smallInnerBox">I'm a small small inner box</div>
</div>
2 拷贝事件处理器(event handler)
以下实例将会拷贝Button的click 事件,你将会拷贝id为cloneButton1的button。
<buttonid="cloneButton1">clone()</button>
<scripttype="text/javascript">
$("#cloneButton1").click(function () {
$('.smallBox').clone().insertAfter(".smallBox");
});
</script>
如果你使用默认的clone()和clone(false)方法,此方法将拷贝button元素,但是不拷贝click()事件处理器。
$('#cloneButton1').clone().insertAfter("#cloneButton1");
为了拷贝匹配元素的click()事件,你应该使用clone(true)来进行拷贝。
$('#cloneButton1').clone(true).insertAfter("#cloneButton1");
具体代码如下:
<html>
<head>
<script type="text/javascript" src="../jquery-1.11.1.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 am a small box
<div class="smallInnerBox">i am small small inner box</div>
</body>
<button id="cloneButton1">clone()</button>
<button id="cloneButton2">clone() button (default)</button>
<button id="cloneButton3">clone(true) button</button>
<button id="reset">reset</button>
<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>
</html>
效果: