jQuery中的jQuery.prepend()和jQuery.prependTo()方法有什么区别?

jQuery.prepend()

prepend(content)方法会将content附加到每个匹配元素的内部。这是此方法使用的所有参数的描述-

  • 内容 -每个目标后插入的内容。这可能是HTML或文本内容

示例

您可以尝试运行以下代码以了解如何prepend()在jQuery中使用方法-

<html>

   <head>
      <title>jQuery prepend() method</title>
      <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).prepend('<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>

jQuery.prependTo()

prependTo(selector)方法会将所有匹配的元素添加到另一组指定的元素之前。

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

  • 选择器 -这是内容要添加到的目标。

示例

您可以尝试运行以下代码以了解如何使用prependTo()方法-

<html>

   <head>
      <title>jQuery prependTo() method</title>
      <script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).prependTo("#result");
            });
         });
      </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>
      <p id = "result"> THIS IS TEST </p>
      <hr />
       
      <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>