• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • last()

    获取匹配元素集合中最后一个元素。

  • .last()
    • 这个方法不接受任何参数。
  • 如果一个jQuery对象表示一个DOM元素的集合,.last()方法从最后一个匹配的元素中构造一个新的jQuery对象。

    考虑一个页面上的一个简单的列表:

    <ul>
      <li>list item 1</li>
      <li>list item 2</li>
      <li>list item 3</li>
      <li>list item 4</li>
      <li>list item 5</li>
    </ul>
    

    我们可以应用此方法设置列表项:

    $('li').last().css('background-color', 'red');
    

    调用的结果是最后一个项目为红色背景。

    例子

    高亮段落中的最后一个span

    <!DOCTYPE html>
    <html>
    <head>
      <style>.highlight{background-color: yellow}</style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
    <script>$("p span").last().addClass('highlight');</script>
     
    </body>
    </html>
    

    Look:This is some text in a paragraph.This is a note about it.

    上篇:first()

    下篇:slice()