2009-10-27 14 views
5

Estoy tratando de encontrar el número de índice del último elemento de la lista, pero el jquery que estoy utilizando sigue arrojando -1. Este es el JS y el html que estoy usando.Obteniendo el índice de un elemento de la lista con Jquery

var index = $('#imageThumbnails li:last').index(this); 

<div id="imageThumbnails"> 
    <ul class="gallery_demo_unstyled"> 
     <li class="active"><img src="test-img.jpg" width="394" height="394" alt=" " /></li> 
     <li><img src="test-img2.jpg" width="394" height="394" alt=" " /></li> 
     <li><img src="test-img3.jpg" width="394" height="394" alt=" " /></li> 
     <li><img src="test-img4.jpg" width="394" height="394" alt=" " /></li> 
     <li><img src="test-img5.jpg" width="394" height="394" alt=" " /></li> 
     <li><img src="test-img6.jpg" width="394" height="394" alt=" " /></li> 
     <li><img src="test-img7.jpg" width="394" height="394" alt=" " /></li> 
    </ul> 
</div> 

Gracias por su ayuda.

Respuesta

21

Necesita llamar al índice en la colección, pasando un subtema de esa colección.

var items = $('#imageThumbnails li'); 
var lastItem = $('#imageThumbnails li:last'); 
var index = items.index(lastItem); 

Si se encuentra en un controlador de función de clic que podría hacer algo como esto:

var items = $('#imageThumbnails li').click(function() { 
    var index = items.index(this); 

    // now that I know where I am, why am I here? 
}); 
+0

Gracias por su ayuda! –

+1

¿cómo funcionaría ese segundo? – TStamper

+0

La variable 'items' se incluye en el cierre de la función interior y estará disponible en el momento en que se ejecute la función de clic. Como ese tiempo será en el futuro, toda la expresión se habrá completado y 'items' se habrá establecido en la matriz de valores que resultó de la expresión. – joshperry

Cuestiones relacionadas