如何使用 jQuery 將元素插入 DOM?


在現有文件中插入一個或多個新的 DOM 元素時可能會出現一種情況。jQuery 提供了多種方法可在不同位置插入元素。

after( content ) 方法在每一個匹配的元素後插入內容,而 before( content ) 方法在每一個匹配的元素前插入內容。

在內容之後

after( content ) 方法在每一個匹配的元素後插入內容。

示例

您可以嘗試執行以下程式碼,瞭解如何使用 after() 方法將元素插入 DOM

即時演示

<html>

   <head>
      <title>jQuery after(content) 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 () {
               $(this).after('<div class = "div"></div>' );
            });
         });
      </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>
       
   </body>
</html>

在內容之前

before( content ) 方法在每一個匹配的元素前插入內容。

示例

您可以嘗試執行以下程式碼,瞭解如何使用 before() 方法將元素插入 DOM

即時演示

<html>

   <head>
      <title>jQuery before(content) 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 () {
               $(this).before('<div class = "div"></div>' );
            });
         });
      </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>
       
   </body>
</html>

更新於: 17-Dec-2019

379 瀏覽

開啟你的 職業生涯

完成課程獲取認證

入門
廣告
© . All rights reserved.