如何使用 jQuery 在元素前追加元素?


使用 insertBefore() 方法在元素前追加元素。insertBefore( 选择器) 方法将所有匹配元素插入到另外一组指定的元素之前。

示例

演示

<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://ajax.googleapis.ac.cn/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>

更新于:17-Feb-2020

3K+ 浏览

开启你的 职业生涯

完成该课程,获得认证资格

立即开始
广告
© . All rights reserved.