2011-09-14 43 views
0

我有下面的代碼片段從一個div訪問第二個元素

<div class='container'> 
       <a href=''> 
        <img alt='' class='image0' src='images/Gallery/gallery-01.jpg' title='info'/> 
       </a> 
       <a href=''> 
        <img alt='' class='image1' src='images/Gallery/gallery-01.jpg' title='info'/> 
       </a> 
       <a href=''> 
        <img alt='' class='image2' src='images/Gallery/gallery-01.jpg' title='info'/> 
       </a> 
      </div> 

我可以用

$('.container a:first')$('.container a:last')訪問第一個和最後一個元素,但我怎麼能訪問第二錨標記在div上? 。

回答

10

使用:eq選擇:

$('.container a:eq(1)') 

或(最好)的.eq功能:

$('container a').eq(1) 
+1

+1使用'eq'功能;它是目前較快的方法,因爲'querySelectorAll'不支持'eq'選擇器。 – lonesomeday

+0

嘗試添加一個點到第二個類,但stackoverflow不允許它。 – nasty

+0

非常感謝,它的工作 – userRaj

0

你可以嘗試$('。container a:first')。next();獲得第二個元素。

0

$('.container a')[1]將返回DOM元素。

$($('.container a')[1])將爲您提供第二個對象的Jquery對象。

適當地檢查你的結果長度。

1

您可以使用:

$('.container a:nth-child(2)') 
相關問題