如何在 DOM 中使用 jQuery 插入一個元素?


在某些情況下,你可能想向現有文件插入一個或多個 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>

更新時間:2019-12-17

376 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.