如何在 jQuery 中使用 jQuery.insertBefore() 方法?


insertBefore(selector) 方法在另一個指定的元素集之前插入所有匹配的元素。以下是此方法使用的所有引數的說明 -

  • selector − 在其之前插入選定元素的內容。

例程

你可以嘗試執行以下程式碼,瞭解如何在 jQuery 中使用 jQuery.insertBefore() 方法 -

即時演示

<html>

   <head>
      <title>jQuery insertBefore() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $("#source").insertBefore(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>
      <div class = "div" id = "source"></div>
       
   </body>
   
</html>

更新時間: 2020 年 2 月 14 日

248 次瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始
廣告