views:

66

answers:

3

I want to get the ID of an element I click on. I put the function in the onclick element, like this:

<a id="myid" class="first active" onclick="markActiveLink();" href="#home">Home</a>

And this is in the function:

function markActiveLink() {   
    alert($(this).attr("id"));
}

This doesn't work, as it says it isn't defined. Does it really forget about the ID, do I have to type it in the onclick?

+3  A: 

Try: onclick="markActiveLink(this);" and

function markActiveLink(el) {   
    alert($(el).attr("id"));
}
No Surprises
+1. This is it. `this` keeps its original scope. If you define it somewhere besides the element itself, `this` is not the element.
Matchu
+6  A: 

why using an inline handler? Move to unobtrusive js

$(document).ready(function(){
  $('#myid').bind('click', function(){
     alert($(this).attr('id'));
  });
});
jAndy
+1. But this is a better solution.
Matchu
Ah, that is a better way to deal with it.
skerit
+3  A: 

You have to pass the element to the function. JS itself isn't smarter than you :)

html:

<a id="myid" class="first active" onclick="markActiveLink(this);" href="#home">Home</a>

js:

function markActiveLink(e) {   
    alert(e.id);
}
Anpher