jQuery last() 方法



jQuery 中的last() 方法用於從匹配元素集中選擇最後一個元素。此方法通常用於定位 jQuery 選擇器選擇的元素集合中的最後一個元素。

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

語法

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

$(selector).last()

引數

此方法不接受任何引數。

示例 1

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

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('p').last().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').last().text('Since Im the last p element inside the last 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').last().text('Since Im the last 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
廣告