Ottenere l'indice di una voce di elenco con Jquery
-
06-07-2019 - |
Domanda
Sto cercando di scoprire il numero indice dell'ultimo elemento dell'elenco ma il jquery che sto usando continua a restituire -1. Questo è il JS e l'html che sto 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>
Grazie per il tuo aiuto.
Soluzione
Devi chiamare l'indice sulla raccolta, passando un sotto-elemento di quella raccolta.
var items = $('#imageThumbnails li');
var lastItem = $('#imageThumbnails li:last');
var index = items.index(lastItem);
Se ti trovi in ??un gestore di funzioni click, potresti fare qualcosa del genere:
var items = $('#imageThumbnails li').click(function() {
var index = items.index(this);
// now that I know where I am, why am I here?
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow