使用 jQuery 新增 DOM 元素的最佳方法是什麼?


使用 jQuery 新增 DOM 元素的最佳方法是使用 append() 方法附加 HTML 字串。你可以嘗試執行以下程式碼插入 DOM 元素 -

示例

即時演示

<html>

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

更新時間: 17-2 月-2020

136 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.