2010-01-02 34 views
10

一定有一些簡單的我很想念。我試圖獲取元素的索引,但保持-1。問題與jQuery索引()

HTML:

<div id="rating_boxes"> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> 
</div> 

的jQuery:

$("img.ratingbox").hover(function() { 
    var index = $(this).parent().index(this); 
      // have also tried $("#rating_boxes").index(this); 
      // and $("#rating_boxes").index($(this)); 
      // and $(this).parent().index($(this)); 
    alert(index); 
    $(this).attr('src', '/img/ratingbox-selected.gif'); 
}, function() { 
    $(this).attr('src', '/img/ratingbox.gif'); 
}); 

回答

23

我傾向於避免在jQuery 1.3.2和之前版本中使用index(),因爲它感覺使用起來不直觀。我只是用

$(this).prevAll().length 

得到的索引。在prevAll()上調用size()只返回length屬性的值,所以我更願意直接使用長度並跳過額外的函數調用。

例如,

$("img.ratingbox").hover(function() { 
    var index = $(this).prevAll().length; 
    alert(index); 
    $(this).attr('src', '/img/ratingbox-selected.gif'); 
}, function() { 
    $(this).attr('src', '/img/ratingbox.gif'); 
}); 

在jQuery的1.4中,只要能夠調用index()一個jQuery對象上得到的對象的第一個元素的索引。

+0

如果可以的話,我會贊成這20次。 .index()沒有意義。 – nipponese 2013-07-30 21:48:56

+0

偉大的方法! – Alexander 2016-04-22 13:55:54

10

index()返回給定元素的索引的元素的列表,而不是一個父元素中。要找到點擊圖像的索引,您需要查找所有圖像,而不是所有圖像的父級

你想是這樣的:

// Find all the images in our parent, and then find our index with that set of images 
var index = $(this).parent().find("img").index(this); 

你也使用id選擇,而不是在你的第二個示例類選擇。取而代之的

$("#rating_boxes").index($(this)); // your way - select by ID 

你想

$(".rating_boxes").index(this); // select by class 
6

如果你想知道的評級框的位置,一個更強大的方法是使用:

var index = $(this).prevAll('img').size(); 

也就是說,計算數量這個元素之前的img元素。索引方法要求您首先選擇父元素,然後選擇裏面的所有img元素。這有點快。