jQuery 中 append() 和 appendTo() 的區別是什麼?
append (content) 方法將內容附加到每個匹配元素的內部,而 appendTo (selector) 方法將所有匹配的元素附加到另一個指定的元素集。
jQuery append() 函式
append (content) 方法將內容附加到每個匹配元素的內部。
以下是此方法使用到的所有引數的說明:
- content − 要在每個目標之後插入的內容。這可以是 HTML 或文字內容
示例
您可以嘗試執行以下程式碼來學習如何在 jQuery 中使用 append() 函式
<html> <head> <title>jQuery append() method</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("div").click(function () { $(this).append('<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 appendTo() 函式
appendTo (selector) 方法將所有匹配的元素附加到另一個指定的元素集。以下是此方法使用到的所有引數的說明:
- selector − 這是將內容附加到的目標。
示例
您可以嘗試執行以下程式碼來學習如何在 jQuery 中使用 appendTo() 函式
<html> <head> <title>jQuery appendTo()</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).appendTo("#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>
廣告