jQuery: Number of element clicked on

I want to know the number of the matched elements click on.  


In the example below, if a user clicks "Hello" then the alert should be "1".
If a user clicks "world" then the alert should be "2".
If a user clicks "test" then the alert should be "3".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
  $('a').click(function() {
    alert( You clicked on link number ??? );
  });
});
</script>

</head>
<body>
<p>
 <a href="#">Hello</a>
 <a href="#">world</a>
 <a href="#">Test</a>
 <a href="#">Link</a>
</p>
</body>
</html>

Open in new window

LVL 16
hankknightAsked:
Who is Participating?
 
HainKurtConnect With a Mentor Sr. System AnalystCommented:
index start from 0, you can add 1 if you wish
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
  $("#myLinks a").each(function(index){
  $(this).click(function(){
    alert("You clicked a:" + index);
  })
});
});
</script>

</head>
<body>
<p id=myLinks>
 <a href="#">Hello</a>
 <a href="#">world</a>
 <a href="#">Test</a>
 <a href="#">Link</a>
</p>
</body>
</html>

Open in new window

0
 
leakim971Connect With a Mentor PluritechnicianCommented:
var link_number = $(this).index($(this).parent().find("a")) + 1;

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.