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

insertBefore(选择器)方法将所有匹配的元素插入到另一组指定的元素之前。这是此方法使用的所有参数的描述-

  • 选择器 -在其之前插入所选元素的内容。

示例

您可以尝试运行以下代码来学习如何在jQuery中使用jQuery.insertBefore()方法-

<html>

   <head>
      <title>jQuery insertBefore() method</title>
      <script src = "https://cdn.staticfile.org/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>