If I define a function like this:
function doSomething()
{
this.style.color = '#cc0000';
}
Do
element.attachEvent('onclick',doSomething)
and
element.addEventListener('click',doSomething,false)
get the same result? And why?Thanks a lot.
-
1No. When using attachEvent in IE, the listener's this keyword is set differently to how it is set by addEventListener in every other browser. In IE, this within the function will be window, in other browsers it will be the element that the listener is attached to.RobG– RobG2011年04月01日 08:04:21 +00:00Commented Apr 1, 2011 at 8:04
-
Am I correct that this code is from this page on PPK's QuirksMode site? What, specifically, are you having trouble with in his explanation?Dori– Dori2011年04月02日 11:29:18 +00:00Commented Apr 2, 2011 at 11:29
2 Answers 2
Yes, but in different browsers.
attachEventis the method you have to use in IE.addEventListeneris available in all other browsers (Firefox, Chrome, Safari, Opera, etc). It is the W3C standard. IE9 tries to be more compatible with W3C and supports it too.
I suggest to read Advanced event registration models which explains the browser differences quite well.
You should also read the other articles about events on quirksmode.org. They will give you a good in event handling in general.
4 Comments
this will be the global object inside doSomething() using attachEvent() whereas it will be the element using addEventListener, so the OP's code won't work in the first case.this problem.