6

I've read most of the relevant articles in quirksmode.org but still I'm not sure about this one:

Making my app compatible with IE8 (fun fun fun) I encounter this issue when trying to set an onclick event to a link:

function myClickHandler(event)
{
    alert(event);
}

var link = document.getElementById("myLink");
link.onclick = myClickHandler; //first option

As opposed to:

function myClickHandler(event)
{
    alert(event);
}

var link = document.getElementById("myLink");
link.onclick = function() {
   myClickHandler(event); //second option
}

Using the first option, myClickHandler alerts undefined. Using the second option alerts [object Event] which makes me believe that the event object isn't passed by the first option to the handler. Why is this so on IE8?

Note: Don't want to use attachEvent as I want to override a single listener during execution and onclick seems to fit here fine.

4

2 回答 2

11

Yes, the event object is not passed as a parameter to DOM0-style event handlers in IE <= 8. You need to get it from window.event instead. If you add a parameter called event, in IE <= 8 this will be undefined and references to event within the event handler will resolve to the undefined parameter rather than window.event. I usually use window.event to make this explicit in the code:

link.onclick = function(evt) {
   evt = evt || window.event;
}
于 2013-08-19T08:46:59.610 回答
0

Once I needed to handle click events on window and work with target property in IE8
The solution that I used in my project:

 document.onclick = function(event) {
                event = event || fixEvent.call(this, window.event);
                var target = event.target || event.srcElement;
                var className = target.className;
                // ....
            };




//For IE8 
// source: https://learn.javascript.ru/fixevent
    function fixEvent(e) {

       e.currentTarget = this;
       e.target = e.srcElement;

       if (e.type == 'mouseover' || e.type == 'mouseenter') e.relatedTarget = e.fromElement;
       if (e.type == 'mouseout' || e.type == 'mouseleave') e.relatedTarget = e.toElement;

       if (e.pageX == null && e.clientX != null) {
           var html = document.documentElement;
           var body = document.body;

           e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0);
           e.pageX -= html.clientLeft || 0;

           e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0);
           e.pageY -= html.clientTop || 0;
       }

       if (!e.which && e.button) {
           e.which = e.button & 1 ? 1 : (e.button & 2 ? 3 : (e.button & 4 ? 2 : 0));
       }

       return e;
   }
于 2016-04-26T15:19:25.810 回答