.first()
.first() 返回: jQuery
描述: 獲取元素集合中第一個(gè)元素。
version added: 1.4.first()
如果一個(gè)jQuery對(duì)象表示一個(gè)DOM元素的集合,.first()方法從最后一個(gè)匹配元素中構(gòu)造一個(gè)新的jQuery對(duì)象。
考慮一個(gè)頁(yè)面上的一個(gè)簡(jiǎn)單的列表:
<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>
我們可以應(yīng)用此方法設(shè)置列表項(xiàng):
$('li').first().css('background-color', 'red');
調(diào)用的結(jié)果是第一個(gè)項(xiàng)目為紅色背景。
Example:
Highlight the first span in a paragraph.
<!DOCTYPE html>
<html>
<head>
<style>.highlight{background-color: yellow}</style>
<script src="http://code.jquery.com/jquery-latest.min.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>