I\'ve come across a head scratching issue with my JavaScript application.
If I write an element like this:
As other answers already mention, the value of this will depend on how the function that contains it is called. But since your example is about event handlers, I'd like to highlight what cjc343 said on the comments:
You may find it to be more sensible if you remove the inline event handlers.
That's pretty simple, actually. Considering this HTML:
- item 1
- item 2
- item 3
The following JavaScript will account for both removing inline handlers, and using delegation:
var list = document.getElementById('list');
list.addEventListener('click', function(evt){
console.log("this is the element the event is bound to: " + this.id);
console.log("the event target is the clicked element: " + evt.target.id);
});
http://jsfiddle.net/J3Gje/
That will work on all browsers compliant to the W3C event model, including IE9. For older IE, you have to use attachEvent instead of addEventListener, and prepend the event names with "on". More details here.