如何使用 jQuery.wrapAll() 來包裹多個元素?


要在 jQuery 中包裹多個元素,請使用 wrapAll() 方法。wrapAll( ) 方法將匹配集中所有的元素都打包到單個包裹元素中。

下面是此方法用到的所有引數的說明

  • html − 一段 HTML 字串,它將在執行時建立,然後包裹在每個目標的周圍。

你可以嘗試執行以下程式碼來學習如何使用 jQuery.wrapAll() 方法來包裹多個元素 −

實際演示

<html>

   <head>
      <title>jQuery wrap() 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 () {
               var content = "<div class = 'div'></div>";
               $("div").wrapAll( content );
            });
         });
      </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" id = "destination">THIS IS TEST</div>
      <div class = "div" style = "background-color:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
       
   </body>
   
</html>

更新於: 2020 年 6 月 13 日

1K+ 次瀏覽

開啟你的 職業生涯

完成課程,獲得證書

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