jQuery 中 jQuery.clone() 方法如何工作?


要使用 jQuery 克隆一個元素,可以使用 jQuery.clone() 方法。clone() 方法克隆匹配的 DOM 元素並選擇克隆體。

這對於將元素的副本移動到 DOM 中其他位置很有用。

示例

你可以嘗試執行以下程式碼來學習如何在 jQuery 中運用 jQuery.clone() 方法

即時演示

<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:15px;
             padding:15px;
             border:4px solid #666;
             width:90px;
         }
      </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 日

153 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

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