You need to wrap alert
in a function. This will work:
ronan.addEventListener("click", function() { alert('Hi'); }, false);
Here's a fiddle for proof. Using alert
alone doesn't work because when a listener is executed the value of this
within that function is set to the object on which it is listening. For example, if you set a listener on ronan
, within that listener this === ronan
. This presents a problem for alert
because that function expects this
to be equal to window
. You can work around this (no pun intended) by wrapping the function in another function or by binding it to whatever it expects this
to be:
document.body.addEventListener('click', alert.bind(window), false);
Don't forget that in IE < 9 you need to use attachEvent
rather than addEventListener
.
A note on using apply
/call
with addEventListener
Your second attempt won't work because you're trying to apply your arguments to window.addEventListener
, as opposed to HTMLElement.prototype.addEventListener
, which is a different function altogether:
// This won't work
addEventListener.apply(ronan, ["click", alert.bind(window), false]);
// This will work
HTMLElement.prototype.addEventListener.apply(ronan, ['click', alert.bind(window), false]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…