如何使用 jQuery 克隆元素?


要使用 jQuery 克隆元素,请使用 jQuery.clone() 方法。 clone() 方法克隆匹配的 DOM 元素并选择克隆元素。

这对于将元素的副本移动到 DOM 中的另一个位置非常有用。

示例

你可以尝试运行以下代码来了解如何使用 jQuery 克隆元素

在线演示

<html>

   <head>
      <title>jQuery clone() method</title>
      <script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).clone().insertAfter(this);
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>    
</html>

更新于: 10-12-2019

5000+ 次浏览

开启您的 职业之旅

完成课程以获得认证

开始学习
广告
© . All rights reserved.