Determine which link was clicked? Always returns undefined. What's wrong?

I am trying to determine which of the first 3 links is clicked by displaying the link identifier.

It always returns undefined .

What's wrong?

 <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> window.onload = function() { onclick = function() { alert(this.id); return false; } } </script> </head> <body> <a class="a" name="a" id="1" href="#">---1---</a> <a class="a" name="a" id="2" href="#">---2---</a> <a class="a" name="a" id="3" href="#">---3---</a> <a href="#"> normal link </a> </body> </html> 
+7
source share
4 answers

You are not targeting any links.

  window.onload = function() { $("aa").click(function() { alert(this.id); return false; }); } 

What it does ( $("aa").click(function(){ ) looks for any click events on the anchors of the class name 'a' and runs the next anonymous function.

+13
source

You have not used any jQuery bits. Check here the jquery version I made on jsfiddle: http://jsfiddle.net/8tu8W/

+4
source

Changed your HTML a bit

 <a class="a" name="a" id="anch1" href="#">---1---</a> <a class="a" name="a" id="anch2" href="#">---2---</a> <a class="a" name="a" id="anch3" href="#">---3---</a> <a href="#"> normal link </a> 

The binding identifiers and the entered document readiness event have been changed.

 $(function(){ $("aa").click(function(){ alert (this.id); }); }); 
+2
source

Something like that. You will add interactive links to the array, and then attach the click event to the document, in the event method you will get the goal to click the mouse, if any, and at what position in the array.

 window.onload = function() { var clickableLinks = []; var links = document.getElementsByTagName("a"); for(var i=0,len=links.length;i< len;i++) { var link = links[i]; if(link.className.split(" ").indexOf("a") != -1) { // Or another detection clickableLinks[clickableLinks.length] = link; } } document.attachEvent('onclick', clicked); // IE document.addEventListener('click', clicked, false); // Other browsers function clicked(event) { var target; if (event.target) {target = event.target}; if (event.srcElement) {target = event.srcElement}; var index = clickableLinks.indexOf(target); if(index != -1) { alert("clicked at", index+1, "link"); } } 
0
source

All Articles