以下是我的JavaScript (mootools)代码:

$('orderNowForm').addEvent('submit', function (event) {
    event.preventDefault();
    allFilled = false;
    $$(".required").each(function (inp) {
        if (inp.getValue() != '') {
            allFilled = true;
        }
    });

    if (!allFilled) {
        $$(".errormsg").setStyle('display', '');
        return;
    } else {
        $$('.defaultText').each(function (input) {
            if (input.getValue() == input.getAttribute('title')) {
                input.setAttribute('value', '');
            }
        });
    }

    this.send({
        onSuccess: function () {
            $('page_1_table').setStyle('display', 'none');
            $('page_2_table').setStyle('display', 'none');
            $('page_3_table').setStyle('display', '');
        }
    });
});

在除IE之外的所有浏览器中,这都可以正常工作。但在IE中,这会导致错误。我有IE8,所以在使用它的JavaScript调试器时,我发现事件对象没有preventDefault方法,这是导致错误的,所以表单被提交。该方法在Firefox(我是使用Firebug发现的)的情况下得到支持。

任何帮助吗?


当前回答

FWIW,如果有人重新审视这个问题以后,你也可以检查你正在处理你的onKeyPress处理函数。

当我错误地传递onKeyPress(this)而不是onKeyPress(event)时,我遇到这个错误。

只是要查点别的。

其他回答

FWIW,如果有人重新审视这个问题以后,你也可以检查你正在处理你的onKeyPress处理函数。

当我错误地传递onKeyPress(this)而不是onKeyPress(event)时,我遇到这个错误。

只是要查点别的。

在IE中,你可以使用

event.returnValue = false;

达到同样的效果。

为了不得到一个错误,你可以测试是否存在preventDefault:

if(event.preventDefault) event.preventDefault();

你可以将两者结合起来:

event.preventDefault ? event.preventDefault() : (event.returnValue = false);

在监听器中返回false应该可以在所有浏览器中工作。

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

Mootools在Event对象中重新定义了preventDefault。因此,您的代码应该在每种浏览器上都能正常工作。如果没有,那么mootools对ie8的支持有问题。

你在ie6和/或ie7上测试过你的代码吗?

医生说

使用addEvent添加的每个事件都会自动获得mootools方法,而不需要手动实例化它。

但万一它没有,你可能想试试

new Event(event).preventDefault();

preventDefault是一个广泛使用的标准;每次你想要兼容旧的IE版本时都使用adhoc是很麻烦的,最好使用polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

这将修改Event的原型并添加此函数,这是javascript/DOM的一个很好的特性。现在您可以毫无问题地使用e.preventDefault了。