jQuery clone()示例

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>

翻译自: https://mkyong.com/jquery/jquery-clone-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值