views:

636

answers:

4
<ul class="bullets">
  <li><a href="#">item 1</a></li>
  <li><a href="#">item 2</a></li>
  <li><a href="#">item 3</a></li>
  <li><a href="#">item 4</a></li>
  <li><a href="#">item 5</a></li>
</ul>

When I click on the <a> element, i'd like to get it's parent <li>'s index number.

I'm trying to create a carrousel type function that doesn't need item-n classes on the list items.

$(".bullets li a").click(function(){

   var myIndex = $(this).parent().index(this);
   showPic(myIndex);

});

Thanks for any help.

TD.

+6  A: 
$(".bullets li a").click(function(){

   var myIndex = $(this).parent().prevAll().length;
   showPic(myIndex);

});


Note: prevAll().length will give you a zero-based index; the first item will be 0 (zero).

J-P
A: 
$(".bullets li a").click(function(){
   var me = $(this);
   var myIndex = $.each($("li", $(this).parent().parent()), function(i, item){
      if(item == me){
      showPic(i);
   });
});
Marius
A bit long-winded, don't you think?
J-P
Thank you both very much!I was looking at the wrong function, stupid .index()
tdskate
A: 
$(".bullets li a").click(function(){
 var myIndex = $(".bullets li a").index(this);
 showPic(myIndex);
});
bjoernwibben
A: 

How I'd do it

$(".bullets li a").click(function()
    {
  var $li = $(this).parent();
  var myIndex = $li.parent().children().index( $li );
  alert( myIndex );
});
Peter Bailey