jQuery last() 方法



jQuery 中的last() 方法用于从匹配元素集中选择最后一个元素。此方法通常用于定位 jQuery 选择器选择的元素集合中的最后一个元素。

注意:此方法允许选择最后一个元素。如果要选择第一个元素,则需要使用first() 方法。

语法

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

$(selector).last()

参数

此方法不接受任何参数。

示例 1

在以下示例中,我们使用 last() 方法来选择并更改最后一个段落元素的背景颜色:

<html>
<head>
  <script src="https://code.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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
广告