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

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

  • .first()
    • 这个方法不接受任何参数。
  • 如果一个jQuery对象表示一个DOM元素的集合,.first()方法会构造一个新的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').first().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").first().addClass('highlight');</script>
     
    </body>
    </html>
    

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

    上篇:eq()

    下篇:last()