如何使用 jQuery 獲取所有匹配元素的文字內容?


要使用 jQuery 獲取所有匹配元素的文字內容,請使用 text() 方法。你可以嘗試執行以下程式碼,以使用 jQuery 獲取所有匹配元素的文字內容 -

示例

線上演示

<html>
   <head>
      <title>The Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {
           $("#button1").click(function(){
             var content = $("#pid2").text();
             alert(content);
           });
         });
      </script>
       
      <style>
       .red {
         color:red;
       }
       .green {
         color:green;
       }
      </style>
   </head>
   
   <body>
      <p class = "green" id = "pid1">This is <i>first paragraph</i>.</p>
      <p class = "red" id = "pid2">This is second paragraph.</p>
      <button id="button1">Get</button>
   </body>
</html>

更新於: 2020-02-14

361 次瀏覽

開啟您的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.