为什么IE9 +上的Web浏览器不支持document.createEvent以及如何修复它?

时间:2014-02-19 18:10:58

标签: c# javascript internet-explorer internet-explorer-9 webbrowser-control

我正在使用Windows 8,Internet Explorer 10,Visual Studio 2013

这是javascript代码:

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (true || document.createEvent) // temporary it's always true to check IE
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
};

我的HTML:

<a href="http://google.com" id="rrx"  > google </a>

这是我的javascript代码,它调用了simulate:

simulate(document.getElementById('rrx'), "click"); 

问题是我没有被重定向到谷歌网页,因为IE会抛出一个异常,但不支持document.createEvent的消息。 据我所知,IE9 +应该支持document.createEvent

1 个答案:

答案 0 :(得分:2)

添加提醒以显示document.documentModedocument.compatMode,您看到了什么?

我相信你应该在注册表中都有正确的FEATURE_BROWSER_EMULATION值,在HTML本身中应该有<!DOCTYPE html>,因为所有现代的HTML DOM / JavaScript功能都可以使用。

这也适用于你的related question