jQuery如何使用clone()方法?代码示例

2021年4月1日15:56:31 发表评论 566 次浏览

clone()是jQuery中的内置方法, 用于复制所选元素(包括其子节点, 文本和属性)。

语法如下:

$(selector).clone(true|false)

参数:

它接受一个可选参数, 该参数可以为true或false, 指定是否应复制事件处理程序。

返回值:

它返回所选元素的克隆元素。

jQuery代码显示此方法的工作方式:

代码1:

在下面的代码中, 不会将true或false传递给change方法。

<html>
  
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/
                jquery/3.3.1/jquery.min.js"></script>
                 
     <!--In this example no parameter is passing to the 
         clone method-->
     <script>
         $(document).ready(function() {
             $("button").click(function() {
                 $("p").clone().appendTo("body");
             });
         });
     </script>
</head>
  
<body>
     <p>Welcome to</p>
     <p>lsbin !!!</p>
     <!--click on this method and see the clone element-->
     <button>Click Me!</button>
</body>
  
</html>

在点击"点击我"按钮之前,

jQuery如何使用clone()方法?代码示例1

点击"点击我"按钮后,

jQuery如何使用clone()方法?代码示例2

代码2:

在下面的代码中, 将true传递给clone方法。

<html>
  
<head>
     <script src="https://ajax.googleapis.com/ajax/libs/
                 jquery/3.3.1/jquery.min.js"></script>
     <!--here clone method is called with the true value passing-->
     <script>
         $(document).ready(function() {
             $("button").click(function() {
                 $("body").append($("p:first").clone(true));
             });
             $("p").click(function() {
                 $(this).animate({
                     fontSize: "+=1px"
                 });
             });
         });
     </script>
</head>
  
<body>
     <p>lsbin !</p>
     <p>Hello Writer !</p>
     <!--click on this method and see the clone element-->
     <button>Click Me!</button>
</body>
  
</html>

在此示例中, 当你单击" lsbin"时, 代码事件处理程序的动画将起作用, 这也将反映在克隆的元素上。

输出如下:

在点击"点击我"按钮之前,

jQuery如何使用clone()方法?代码示例3

点击"点击我"按钮后,

jQuery如何使用clone()方法?代码示例4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: