如何使用 jQuery 替換 DOM 元素為指定的 HTML 或 DOM 元素?


要使用 jQuery 替換 DOM 元素為指定的 HTML 或 DOM 元素,請使用 replaceWith() 方法。replaceWith (content) 方法將所有匹配的元素替換為指定的 HTML 或 DOM 元素。這將返回剛剛被替換的 jQuery 元素,該元素已被從 DOM 中移除。

示例

你可以嘗試執行以下程式碼以瞭解如何用指定的 HTML 或 DOM 元素替換 DOM 元素

線上演示

<html>

   <head>
      <title>jQuery replaceWith() 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).replaceWith( ('<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:yellow;">ONE</div>
      <div class = "div" style = "background-color:maroon;">TWO</div>
      <div class = "div" style = "background-color:blue;">THREE</div>
       
   </body>
</html>

更新於: 17-Dec-2019

7K+ 瀏覽量

開啟你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.