简体   繁体   English

event.cancel 在 IE11 中的使用

[英]event.cancel usage in IE11

I have an old application that contains the following JavaScript code to handle a key-down event:我有一个旧应用程序,其中包含以下用于处理按键按下事件的 JavaScript 代码:

if (event.keyCode == 13) {
    event.cancel = true;
    document.getElementById(btnId).click();
    return false;
}

return true;

What it should do is to check if the user pressed the enter key, and if so simulate a click on a button and do not execute the default action of the key-down event.它应该做的是检查用户是否按下了 Enter 键,如果是,则模拟单击按钮,并且不执行 key-down 事件的默认操作。

This works fine in Google Chrome, Firefox and IE8.这在 Google Chrome、Firefox 和 IE8 中运行良好。 However, it does not work in IE11.但是,它在 IE11 中不起作用。 How can I make this code work in IE11?如何使此代码在 IE11 中工作?

The problem is that setting event.cancel to false does not do anything in IE11.问题是将event.cancel设置为false在 IE11 中没有任何作用。 The accepted way to cancel the default event handling is to use the event.preventDefault() function.取消默认事件处理的公认方法是使用event.preventDefault()函数。 The following code fixes the problem and works on IE11, Chrome and Firefox:以下代码修复了该问题并适用于 IE11、Chrome 和 Firefox:

if (event.keyCode == 13) {
    event.preventDefault();
    document.getElementById(btnId).click();
    return false;
}

return true;

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

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