Determine the index of image in a div I've clicked on
I've got some code like so:
<div id="thumbs">
<img src="/media/img/banana.png" />
<img src="/media/img/apple.png" />
<img src="/media/img/lobster.png" />
<img src="/media/img/charismatic_duck.png" />
</div>
What I'd like is to work out what the following code needs so that it logs 1 if I click the first image, 2 if I click the next etc.
$("#thumbs img").click(function(){
console.log(_____WHAT GOES HERE?_____)
});
I'm aware that I could add IDs (image1, image2 etc) and use that to work it 开发者_开发百科out, but I'd like a cleaner way if there is one.
console.log( $(this).index() + 1 )
The .index()
method returns a zero-based index number of the img
that was clicked (in relation to its siblings).
I added + 1
to give you the 1-based index that you wanted.
- http://api.jquery.com/index/
There are various other ways of calling .index()
. With no arguments, it behaves as I described above.
精彩评论