如何使用 jQuery 從 DOM 中移除一個元素?


empty() 方法會從匹配元素集合中刪除所有子節點,而 remove() 方法會從 DOM 中刪除所有匹配元素。

要刪除一個元素,請使用 remove() 方法。

示例

你可以嘗試執行以下程式碼,學習如何使用 jQuery 從 DOM 中刪除一個元素

線上示例

<html>
   <head>
      <title>jQuery remove() 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).remove( );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below:</p>
      <span id = "result"> </span>
       
      <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 日

864 瀏覽

開啟你的事業

透過完成課程獲得認證

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