jQuery first() 示例


jQuery first() 方法從指定元素中選擇第一個元素。

語法

語法如下 −

$(selector).first()

例項

現在我們看一個實現 jQuery first() 方法的示例 −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("p").first().css("color", "blue");
   });
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is a line. </p>
<p>This is another line.</p>
<p>This is line 3.</p>
</body>
</html>

輸出

這將產生以下輸出 −

例項

我們再看另一個示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   .one {
      background-color: orange;
      border: 2px dashed red;
   }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("p").first().addClass("one");
   });
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is a line. </p>
<p>This is another line.</p>
<p>This is line 3.</p>
<p>This is line 4.</p>
<p>This is line 5.</p>
</body>
</html>

輸出

這將產生以下輸出 −

更新於: 12-Nov-2019

122 瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.