2010-01-02 4 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 

을 사용합니다. size()prevAll()으로 호출하면 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에서, 당신은 단순히 객체의 첫 번째 요소의 인덱스를 얻기 위해 jQuery를 객체에 index()를 호출 할 수 있습니다.

+0

만약 내가 할 수 있으면 20 회 upvote 것이다. .index()는 의미가 없습니다. – nipponese

+0

큰 접근! – Alexander

10

index()하지의 부모 요소에서, 요소 목록에 지정된 요소의 인덱스를 반환합니다. 클릭 한 이미지의 색인을 찾으려면 모든 이미지 중 부모이 아닌 모든 이미지를 찾아야합니다. 당신은 또한 ID 선택기 대신하여 2 예에서 클래스 선택기를 사용하고

// 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); 

:

당신이 뭔가를 할 수 있습니다.

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

즉, 수를 계산 대신 당신은 평가 상자의 위치를 ​​알고 싶다면 당신은

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

을 원하는

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

의,보다 강력한 방법은 사용하는 것입니다 이 요소 앞의 img 요소들. 색인 방법을 사용하려면 먼저 상위 요소를 선택한 다음 내부에있는 모든 img 요소를 선택해야합니다. 이것은 조금 더 빠릅니다.