如何使用 jQuery 向每個匹配的元素內部新增內容?


要使用 jQuery 向每個匹配的元素內部新增內容,請使用 prepend() 方法。以下是該方法使用的引數的描述

  • content − 在每個目標之後插入的內容。這可以是 HTML 或文字內容

示例

你可以嘗試執行以下程式碼,使用 jQuery 向每個匹配的元素內部新增內容 −

現場演示

<html>

   <head>
      <title>jQuery prepend() method</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).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>

更新於:14-2 月-2020

91 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

立即開始
廣告