以下是我的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发现的)的情况下得到支持。

任何帮助吗?


当前回答

if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

在IE 9和Chrome上测试。

其他回答

一个带有函数检查的方法帮助了我。该方法适用于IE8

if(typeof e.preventDefault == 'function'){
  e.preventDefault();
} else {
  e.returnValue = false;
}

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

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

如果你通过mootools的addEvent函数绑定事件,你的事件处理程序将得到一个固定的(增强的)事件作为参数传递。它将始终包含preventDefault()方法。

试试这个小提琴,看看事件绑定的区别。 http://jsfiddle.net/pFqrY/8/

// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
 alert(typeof(event.preventDefault));
});

// preventDefault missing in IE
<button
  id="htmlbutton"
  onclick="alert(typeof(event.preventDefault));">
  button</button>

对于所有jQuery用户,您都可以在需要时修复事件。说你使用HTML onclick="..",并获得一个IE特定的事件,缺乏preventDefault(),只需使用这段代码来获得它。

e = $.event.fix(e);

之后e.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了。

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

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

只是要查点别的。