如何使用 jQuery 刪除 DOM 元素?


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

示例

你可以嘗試執行以下程式碼,瞭解如何在 jQuery 中移除 DOM 元素

線上演示

<html>
   <head>
      <title>jQuery Example</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 月 9 日

448 次瀏覽

開啟你的 職業生涯

完成課程取得認證

開始吧
廣告
© . All rights reserved.