Obtener el índice de un elemento de la lista con Jquery
-
06-07-2019 - |
Pregunta
Estoy tratando de averiguar el número de índice del último elemento de la lista, pero el jquery que estoy usando sigue devolviendo -1. Este es el JS y el html que estoy usando.
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.
Solución
Debe llamar al índice en la colección, pasando un sub-elemento de esa colección.
var items = $('#imageThumbnails li');
var lastItem = $('#imageThumbnails li:last');
var index = items.index(lastItem);
Si está en un controlador de función de clic, 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?
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow