jQuery 遍歷 - eq() 方法
阿新 • • 發佈:2017-05-18
集合 text nbsp 指示 clas src css doc 如果
<!DOCTYPE html> <html> <head> <style> div { width:60px; height:60px; margin:10px; float:left; border:2px solid blue; } .blue { background:blue; } </style> <script type="text/javascript" src="/jquery/jquery.js"></script> </head> <body> <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> <script>$(‘li‘).eq(2).css(‘background-color‘, ‘red‘);</script> </body> </html>
定義和用法
eq(index) 方法將匹配元素集縮減值指定 index 上的一個。
index:整數,指示元素的位置(最小為 0)。如果是負數,則從集合中的最後一個元素往回計數。
上面的例子調用的結果是為項目 3 設置了紅色背景。請註意,index 是基於零的,並且是在 jQuery 對象中引用元素的位置,而不是在 DOM 樹中
$(‘li‘).eq(2).css(‘background-color‘, ‘red‘);
如果提供負數,則指示從集合結尾開始的位置,而不是從開頭開始。
$(‘li‘).eq(-2).css(‘background-color‘, ‘red‘);
如果無法根據指定的 index 參數找到元素,則該方法構造帶有空集的 jQuery 對象,length 屬性為 0
$(‘li‘).eq(5).css(‘background-color‘, ‘red‘);
jQuery 遍歷 - eq() 方法