addEvent给出null事件对象

时间:2012-08-12 06:01:06

标签: javascript internet-explorer events internet-explorer-8 addeventlistener

我正在尝试在我的项目中获得IE8支持,并且很难将addEventListener转换为addEvent(来自:http://ejohn.org/projects/flexible-javascript-events/

所以,使用他的代码,我有一个类似(source here)的事件设置:

_addEvent(eventableIframes[i], 'mousemove', function (e) {
  utilBarHandler(e);
});

但是,当它到达utilBarHandler时,“e”为null,IE8为我提供了“需要对象”错误here on line 783。我假设所需的对象是事件对象,因为当我在top of the function注销e时,它实际上只是null。

此外,对于该循环中需要shortcutHandlershortcutUpHandler等事件对象的每个事件都会发生这种情况。

更新:以防人们错过它,这篇文章有很多突出显示特定行的链接。

1 个答案:

答案 0 :(得分:2)

并非所有版本的IE都将该事件作为参数传递。它在window.event中。您可以将它添加到_addEvent垫片或事件处理程序:

 e = e || window.event

如:

_addEvent(eventableIframes[i], 'mousemove', function (e) {
      e = e || window.event;
      utilBarHandler(e);
});

可以在IE或其他网站中使用。

这里有两种跨浏览器事件处理方式,可确保在IE中正确设置eventthis指针:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}


// refined add event cross browser
function addEvent(elem, event, fn) {
    // avoid memory overhead of new anonymous functions for every event handler that's installed
    // by using local functions
    function listenHandler(e) {
        var ret = fn.apply(this, arguments);
        if (ret === false) {
            e.stopPropagation();
            e.preventDefault();
        }
        return(ret);
    }

    function attachHandler() {
        // set the this pointer same as addEventListener when fn is called
        // and make sure the event is passed to the fn also so that works the same too
        var ret = fn.call(elem, window.event);   
        if (ret === false) {
            window.event.returnValue = false;
            window.event.cancelBubble = true;
        }
        return(ret);
    }

    if (elem.addEventListener) {
        elem.addEventListener(event, listenHandler, false);
    } else {
        elem.attachEvent("on" + event, attachHandler);
    }
}