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


使用 insertBefore() 方法在元素前追加元素。insertBefore( 選擇器) 方法將所有匹配元素插入到另外一組指定的元素之前。

示例

演示

<html>

   <head>
      <title>The jQuery Example</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>

更新於:17-Feb-2020

3K+ 瀏覽

開啟你的 職業生涯

完成該課程,獲得認證資格

立即開始
廣告
© . All rights reserved.