In IE you have to use attachEvent
rather than the standard addEventListener
.
A common practice is to check if the addEventListener
method is available and use it, otherwise use attachEvent
:
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
You can make a function to do it:
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
alert('element clicked');
});
You can run an example of the above code here.
The third argument of addEventListener
is useCapture
; if true, it indicates that the user wishes to initiate event capturing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…