用jQuery添加DOM元素的最佳方法是什么?


本文向大家介绍用jQuery添加DOM元素的最佳方法是什么?,包括了用jQuery添加DOM元素的最佳方法是什么?的使用技巧和注意事项,需要的朋友参考一下

用jQuery添加DOM元素的最佳方法是使用append()方法附加HTML字符串。您可以尝试运行以下代码来插入DOM元素-

示例

<html>

   <head>
      <title>The jQuery Example</title>
      <script src = "https://cdn.staticfile.org/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:yellow;"></div>
      <div class = "div" style = "background-color:gray;"></div>
      <div class = "div" style = "background-color:green;"></div>
       
   </body>
</html>