简体   繁体   中英

event.cancel usage in IE11

I have an old application that contains the following JavaScript code to handle a key-down event:

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.

This works fine in Google Chrome, Firefox and IE8. However, it does not work in IE11. How can I make this code work in IE11?

The problem is that setting event.cancel to false does not do anything in IE11. The accepted way to cancel the default event handling is to use the event.preventDefault() function. The following code fixes the problem and works on IE11, Chrome and Firefox:

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

return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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