如何在 jQuery 中向每個匹配的元素內部前置內容?


要使用 jQuery 向每個匹配的元素內部前置內容,請使用 prepend() 方法。以下是對該方法使用的引數進行說明

  • 內容 − 插入到每個目標內容後的內容。這可以是 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>

更新於: 2020-02-14

91 瀏覽量

啟動您的職業生涯 生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.