jQuery first() 方法



jQuery 中的first()方法用於選擇匹配元素集中的第一個元素。它檢索匹配元素集中的第一個元素。此方法通常與其他 jQuery 方法結合使用,以操作或檢索文件或一組元素中的特定元素。

注意:此方法允許選擇第一個元素。如果要選擇最後一個元素,則需要使用last()方法。

語法

以下是 jQuery 中 first() 方法的語法:

$(selector).first()

引數

此方法不接受任何引數。

示例 1

在下面的示例中,我們使用 first() 方法來選擇並更改第一個段落元素的背景顏色:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('p').first().css("background-color", "yellow");
    });
  </script>
</head>
<body>
  <div>
  <p>This is the first paragraph.</p>
  <p>This is the second paragraph.</p>
  </div>
</body>
</html>

執行上述程式後,DOM 中的第一個段落元素將被選中,其背景顏色將更改為黃色。

示例 2

在下面的示例中,我們選擇並修改第一個div元素內的第一個p元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('div p').first().text('Since Im the first p element inside the first div element, I got modified...');
    });
  </script>
</head>
<body>
<div>
  <p>Paragraph element 1.</p>
  <p>Paragraph element 2.</p>
</div>
<div>
  <p>Paragraph element 1.</p>
  <p>Paragraph element 2.</p>
</div>
</body>
</html>

執行上述程式後,第一個div元素內的第一個p元素將被選中,其文字將被修改。

示例 3

在這裡,我們選擇並修改列表中的第一項:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('ul li').first().text('Since Im the first element, I got modified...');
    });
  </script>
</head>
<body>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</body>
</html>

如果我們執行程式,第一個li元素將被選中,其文字將被修改。

jquery_ref_traversing.htm
廣告
© . All rights reserved.