简体   繁体   English

event.preventDefault() function 在 IE 中不工作

[英]event.preventDefault() function not working in IE

Following is my JavaScript (mootools) code:以下是我的 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', '');
        }
    });
});

In all browsers except IE, this works fine.在除 IE 之外的所有浏览器中,这都可以正常工作。 But in IE, this causes an error.但在 IE 中,这会导致错误。 I have IE8 so while using its JavaScript debugger, I found out that the event object does not have a preventDefault method which is causing the error and so the form is getting submitted.我有 IE8,因此在使用其 JavaScript 调试器时,我发现event object 没有导致错误的preventDefault方法,因此正在提交表单。 The method is supported in case of Firefox (which I found out using Firebug).该方法在 Firefox(我使用 Firebug 发现)的情况下受支持。

Any Help?有帮助吗?

in IE, you can use在 IE 中,你可以使用

event.returnValue = false;

to achieve the same result.达到相同的结果。

And in order not to get an error, you can test for the existence of preventDefault:为了不出错,您可以测试 preventDefault 是否存在:

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

You can combine the two with:您可以将两者结合起来:

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

If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter.如果您通过 mootools 的 addEvent function 绑定事件,您的事件处理程序将获得作为参数传递的固定(增强)事件。 It will always contain the preventDefault() method.它将始终包含 preventDefault() 方法。

Try out this fiddle to see the difference in event binding.试试这个小提琴,看看事件绑定的区别。 http://jsfiddle.net/pFqrY/8/ 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>

For all jQuery users out there you can fix an event when needed.对于所有jQuery用户,您可以在需要时修复事件。 Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.假设您使用了 HTML onclick=".." 并获得了一个缺少 preventDefault() 的 IE 特定事件,只需使用此代码即可获得它。

e = $.event.fix(e);

After that e.preventDefault();在那之后 e.preventDefault(); works fine.工作正常。

I know this is quite an old post but I just spent some time trying to make this work in IE8.我知道这是一篇很老的帖子,但我只是花了一些时间尝试在 IE8 中让它工作。

It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.看来 IE8 版本中存在一些差异,因为此处和其他线程中发布的解决方案对我不起作用。

Let's say that we have this code:假设我们有这段代码:

$('a').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.在我的 IE8 中,由于 jQuery 存在preventDefault()方法,但无法正常工作(可能是因为以下几点),因此这将失败。

Even if I set returnValue property directly to false:即使我将returnValue属性直接设置为 false:

$('a').on('click', function(event) {
    event.returnValue = false;
    event.preventDefault();
});

This also won't work, because I just set some property of jQuery custom event object.这也行不通,因为我只是设置了 jQuery 自定义事件 object 的一些属性。

Only solution that works for me is to set property returnValue of global variable event like this:唯一对我有用的解决方案是像这样设置全局变量event的属性returnValue

$('a').on('click', function(event) {
    if (window.event) {
        window.event.returnValue = false;
    }
    event.preventDefault();
});

Just to make it easier for someone who will try to convince IE8 to work.只是为了让试图说服 IE8 工作的人更容易。 I hope that IE8 will die horribly in painful death soon.希望IE8早日在痛苦的死亡中惨死。

UPDATE:更新:

As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one.正如sv_in指出的那样,您可以使用event.originalEvent获取原始事件 object 并在原始事件中设置returnValue属性。 But I haven't tested it in my IE8 yet.但我还没有在我的 IE8 中测试过它。

Mootools redefines preventDefault in Event objects. Mootools 在 Event 对象中重新定义了 preventDefault。 So your code should work fine on every browser.所以你的代码应该在每个浏览器上都能正常工作。 If it doesn't, then there's a problem with ie8 support in mootools.如果不是,则 mootools 中的 ie8 支持存在问题。

Did you test your code on ie6 and/or ie7?您是否在 ie6 和/或 ie7 上测试了您的代码?

The doc says医生说

Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.使用 addEvent 添加的每个事件都会自动获取 mootools 方法,无需手动实例化它。

but in case it doesn't, you might want to try但如果没有,您可能想尝试

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

Tested on IE 9 and Chrome.在 IE 9 和 Chrome 上测试。

To disable a keyboard key after IE9, use: e.preventDefault();要在 IE9 之后禁用键盘键,请使用: e.preventDefault();

To disable a regular keyboard key under IE7/8, use: e.returnValue = false;要在 IE7/8 下禁用常规键盘键,请使用: e.returnValue = false; or return false;return false;

If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F ) you need to add those lines:如果您尝试禁用键盘快捷键(使用 Ctrl,如Ctrl+F ),您需要添加这些行:

try {
    e.keyCode = 0;
}catch (e) {}

Here is a full example for IE7/8 only:以下是仅适用于 IE7/8 的完整示例:

document.attachEvent("onkeydown", function () {
    var e = window.event;

    //Ctrl+F or F3
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        //Prevent for Ctrl+...
        try {
            e.keyCode = 0;
        }catch (e) {}

        //prevent default (could also use e.returnValue = false;)
        return false;
    }
});

Reference: How to disable keyboard shortcuts in IE7 / IE8参考: 如何在 IE7 / IE8 中禁用键盘快捷键

Here's a function I've been testing with jquery 1.3.2 and 09-18-2009's nightly build.这是一个 function,我一直在使用 jquery 1.3.2 和 09-18-2009 的夜间构建进行测试。 Let me know your results with it.让我知道你的结果。 Everything executes fine on this end in Safari, FF, Opera on OSX.在 Safari、FF、OSX 上的 Opera 中,一切都在这一端执行良好。 It is exclusively for fixing a problematic IE8 bug, and may have unintended results:它专门用于修复有问题的 IE8 错误,可能会产生意想不到的结果:

function ie8SafePreventEvent(e) {
    if (e.preventDefault) {
        e.preventDefault()
    } else {
        e.stop()
    };

    e.returnValue = false;
    e.stopPropagation();
}

Usage:用法:

$('a').click(function (e) {
    // Execute code here
    ie8SafePreventEvent(e);
    return false;
})

preventDefault is a widespread standard; preventDefault是一个广泛使用的标准; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:每次要与旧 IE 版本兼容时都使用 adhoc 很麻烦,最好使用 polyfill:

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

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general.这将修改 Event 的原型并添加这个 function,这是 javascript/DOM 的一般特性。 Now you can use e.preventDefault with no problem.现在您可以毫无问题地使用e.preventDefault了。

return false in your listener should work in all browsers.在您的侦听器中return false应该适用于所有浏览器。

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

FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function. FWIW,以防万一以后有人重新审视这个问题,您还可以检查您交给 onKeyPress 处理程序 function 的内容。

I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).当我错误地传递 onKeyPress(this) 而不是 onKeyPress(event) 时,我遇到了这个错误。

Just something else to check.只是其他要检查的东西。

I was helped by a method with a function check.一种带有 function 检查的方法帮助了我。 This method works in IE8此方法适用于IE8

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM