加载中...

last()


概述    .last()

返回值:jQuery

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

  • V : 1.4.last()

    • 这个方法不接受任何参数。

如果一个jQuery对象表示一个DOM元素的集合,.last()方法从最后一个匹配的元素中构造一个新的jQuery对象。

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

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

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

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

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

示例

高亮段落中的最后一个span

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>.highlight{background-color: yellow}</style>
  5. <script src="http://code.jquery.com/jquery-latest.js"></script>
  6. </head>
  7. <body>
  8. <p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
  9. <script>$("p span").last().addClass('highlight');</script>
  10. </body>
  11. </html>

运行一下


还没有评论.