jQuery中的jQuery.replaceAll()和jQuery.replaceWith()方法有什么区别?

jQuery.replaceAll()

replaceAll(selector)方法用匹配的元素替换指定选择器匹配的元素。

这是此方法使用的所有参数的描述-

  • 选择器 -查找和替换匹配元素的元素。

示例

您可以尝试运行以下代码来学习如何使用jQuery.replaceAll()方法:

<html>

   <head>
      <title>jQuery replaceAll() method</title>
      <script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $('<div class = "div"></div>').replaceAll( this );
            });
         });
      </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;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
       
   </body>
   
</html>

jQuery.replaceWith()

replaceWith(content)方法将所有匹配的元素替换为指定的HTML或DOM元素。这将返回刚刚被替换的jQuery元素,该元素已从DOM中删除。

这是此方法使用的所有参数的描述-

  • 内容 -替换匹配元素的内容。

示例

您可以尝试运行以下代码来学习如何使用jQuery.replaceWith()方法:

<html>

   <head>
      <title>jQuery replaceWith() method</title>
      <script src = "https://cdn.staticfile.org/jquery/2.1.3/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:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
       
   </body>
   
</html>