如何使用 jQuery 克隆元素?


使用 jQuery 克隆元素的方法是 jQuery.clone() 方法。clone() 方法克隆匹配的 DOM 元素,並選擇這些克隆體。

此方法可用於將元素的副本移動到 DOM 的另一個位置。

示例

可以嘗試執行以下程式碼,瞭解如何使用 jQuery 克隆元素

線上演示

<html>

   <head>
      <title>jQuery clone() method</title>
      <script src = "https://ajax.googleapis.com/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>

更新時間: 2019 年 12 月 10 日

5000+ 次閱讀

開啟你的 職業生涯

透過完成課程進行認證

開始學習
廣告
© . All rights reserved.